| id | chat_gpt_response | question | badsmell_base | bad_smell_gpt | found_any | valid_bad_smell | bad_smell_in_base | bad_smell_not_in_the_base | bad_smell_not_found | index | index_base | url_github | nr_question | id_source_code | id_base | severity |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1192 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ZooInspectorPanel extends JPanel implements NodeViewersChangeListener { private final IconResource iconResource; private final Toolbar toolbar; private final ZooInspectorNodeViewersPanel nodeViewersPanel; private final ZooInspectorTreeViewer treeViewer; private final ZooInspectorManager zooInspectorManager; private final List listeners = new ArrayList(); { listeners.add(this); } /** * @param zooInspectorManager * - the {@link ZooInspectorManager} for the application */ public ZooInspectorPanel(final ZooInspectorManager zooInspectorManager, final IconResource iconResource) { this.zooInspectorManager = zooInspectorManager; this.iconResource = iconResource; toolbar = new Toolbar(iconResource); final List nodeViewers = new ArrayList(); try { List defaultNodeViewersClassNames = this.zooInspectorManager .getDefaultNodeViewerConfiguration(); for (String className : defaultNodeViewersClassNames) { nodeViewers.add((ZooInspectorNodeViewer) Class.forName( className).newInstance()); } } catch (Exception ex) { LoggerFactory.getLogger().error( "Error loading default node viewers.", ex); JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Error loading default node viewers: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } nodeViewersPanel = new ZooInspectorNodeViewersPanel( zooInspectorManager, nodeViewers); treeViewer = new ZooInspectorTreeViewer(zooInspectorManager, nodeViewersPanel, iconResource); this.setLayout(new BorderLayout()); toolbar.addActionListener(Toolbar.Button.connect, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorConnectionPropertiesDialog zicpd = new ZooInspectorConnectionPropertiesDialog( zooInspectorManager.getLastConnectionProps(), zooInspectorManager.getConnectionPropertiesTemplate(), ZooInspectorPanel.this); zicpd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.disconnect, new ActionListener() { public void actionPerformed(ActionEvent e) { disconnect(); } }); toolbar.addActionListener(Toolbar.Button.refresh, new ActionListener() { public void actionPerformed(ActionEvent e) { treeViewer.refreshView(); } }); toolbar.addActionListener(Toolbar.Button.addNode, new AddNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.deleteNode, new DeleteNodeAction(this, treeViewer, zooInspectorManager)); toolbar.addActionListener(Toolbar.Button.nodeViewers, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorNodeViewersDialog nvd = new ZooInspectorNodeViewersDialog( JOptionPane.getRootFrame(), nodeViewers, listeners, zooInspectorManager, iconResource); nvd.setVisible(true); } }); toolbar.addActionListener(Toolbar.Button.about, new ActionListener() { public void actionPerformed(ActionEvent e) { ZooInspectorAboutDialog zicpd = new ZooInspectorAboutDialog( JOptionPane.getRootFrame(), iconResource); zicpd.setVisible(true); } }); JScrollPane treeScroller = new JScrollPane(treeViewer); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroller, nodeViewersPanel); splitPane.setResizeWeight(0.25); this.add(splitPane, BorderLayout.CENTER); this.add(toolbar.getJToolBar(), BorderLayout.NORTH); } /** * @param connectionProps * the {@link Properties} for connecting to the zookeeper * instance */ public void connect(final Properties connectionProps) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { zooInspectorManager.setLastConnectionProps(connectionProps); return zooInspectorManager.connect(connectionProps); } @Override protected void done() { try { if (get()) { treeViewer.refreshView(); toolbar.toggleButtons(true); } else { JOptionPane.showMessageDialog(ZooInspectorPanel.this, "Unable to connect to zookeeper", "Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while connecting to ZooKeeper server", e); } } }; worker.execute(); } /** * */ public void disconnect() { disconnect(false); } /** * @param wait * - set this to true if the method should only return once the * application has successfully disconnected */ public void disconnect(boolean wait) { SwingWorker worker = new SwingWorker() { @Override protected Boolean doInBackground() throws Exception { return ZooInspectorPanel.this.zooInspectorManager.disconnect(); } @Override protected void done() { try { if (get()) { treeViewer.clearView(); toolbar.toggleButtons(false); } } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } catch (ExecutionException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } }; worker.execute(); if (wait) { while (!worker.isDone()) { try { Thread.sleep(100); } catch (InterruptedException e) { LoggerFactory .getLogger() .error( "Error occurred while disconnecting from ZooKeeper server", e); } } } } /* * (non-Javadoc) * * @seeorg.apache.zookeeper.inspector.gui.NodeViewersChangeListener# * nodeViewersChanged(java.util.List) */ public void nodeViewersChanged(List newViewers) { this.nodeViewersPanel.setNodeViewers(newViewers); } /** * @param connectionProps * @throws IOException */ public void setdefaultConnectionProps(Properties connectionProps) throws IOException { this.zooInspectorManager.saveDefaultConnectionFile(connectionProps); } } |
blob | blob, long method | t | t | t | long method | 0 | 10257 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/org/apache/zookeeper/inspector/gui/ZooInspectorPanel.java/#L46-L258 | 1 | 1192 | 10257 | minor | |
| 1568 | {"response": "YES I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | 1. data class | t | t | t | 0 | 11331 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 1568 | 11331 | minor | ||
| 429 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 429 | 4276 | critical | ||
| 81 | {"message": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 1189 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 81 | 1189 | minor | |
| 5649 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method | t | f | t | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 1 | 5649 | 11206 | major | ||
| 1197 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | long method, data class | t | t | t | data class | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1197 | 10271 | critical | |
| 2100 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inconsistent indentation 5. Duplicate code 6. Inconsistent naming convention | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class4 Inconsistent indentation5 Duplicate code6 Inconsistent naming convention | t | f | t | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 2100 | 13158 | minor | ||
| 2609 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | data class | t | t | t | 0 | 15033 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 1 | 2609 | 15033 | minor | ||
| 381 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean isVisible(final IStructuredSelection selection) { final ChangeItem[] changes = (ChangeItem[]) SelectionUtils.selectionToArray(getSelection(), ChangeItem.class); // Enable for any delete for (final ChangeItem change : changes) { if (change.getChangeType().contains(ChangeType.DELETE)) { return true; } } return false; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 3908 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/dialogs/vc/candidates/RestoreAction.java/#L55-L66 | 1 | 381 | 3908 | minor |
| 1414 | { "response": "YES I found bad smells", "detected_bad_smells": { "1": "Blob", "2": "Data Class" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | 1: blob, 2: data class | t | t | t | 1: blob | 0 | 10909 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1414 | 10909 | major | |
| 3840 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 3840 | 9895 | major | ||
| 5759 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Long parameter list"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5759 | 14515 | major | |
| 246 | { "message": "YES I found bad smells", "bad_smells_are": ["1. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | 1. data class | t | t | t | 0 | 2654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 1 | 246 | 2654 | minor | ||
| 3940 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 3940 | 10313 | major | ||
| 1492 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 11118 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1492 | 11118 | critical | |
| 716 | YES I found bad smells the bad smells are: Feature envy, Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | Feature envy, Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | t | f | t | Long method, Duplicate code, Primitive obsession, Shotgun surgery, Message chain | 0 | 6822 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 716 | 6822 | minor | |
| 1109 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
data class | data class, long method | t | t | t | long method | 0 | 9883 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 1 | 1109 | 9883 | minor | |
| 1906 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Conditional complexity 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Conditional complexity5 Feature envy | t | f | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 1906 | 12380 | critical | ||
| 1446 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | blob, long method | t | t | t | blob | 0 | 10983 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 1 | 1446 | 10983 | major | |
| 1746 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1746 | 11853 | minor | ||
| 1118 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 9959 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1118 | 9959 | critical | ||
| 577 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5782 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 577 | 5782 | major | ||
| 1010 | YES, I found bad smells the bad smells are: 1 - Long method 2 - Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | - Long method2 - Feature envy | t | f | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1010 | 9270 | minor | ||
| 1204 | {"response":"YES I found bad smells","bad smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method | t | t | t | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 1204 | 10287 | critical | ||
| 1124 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10000 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 1 | 1124 | 10000 | minor | |
| 2247 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | data class, long method | t | t | t | long method | 0 | 13660 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 1 | 2247 | 13660 | minor | |
| 4676 | YES I found bad smells the bad smells are: 1. Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance). 2. Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class). 3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain). 4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex). 5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code). 6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality). 7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method (the method is too long and can be broken down into smaller methods for better readability and maintenance)2 Feature envy (the method is constantly accessing and manipulating data from external objects, which can indicate that it belongs in a different class)3 Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain)4 Nested loops (there are nested for loops, which can decrease performance and make the code more complex)5 Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code)6 Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality)7 Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow) | t | f | t | which can indicate that it belongs in a different class).3. Magic numbers (there are a few instances where specific values are hardcoded, which can make the code less flexible and harder to maintain).4. Nested loops (there are nested for loops, which can decrease performance and make the code more complex).5. Poor naming/conventions (the use of abbreviations and uninformative variable names make it harder to understand the code).6. Lack of comments/documentation (the code lacks proper comments and documentation, making it harder for other developers to understand its purpose and functionality).7. Inconsistent formatting (the use of inconsistent indentation and spacing can make the code harder to read and follow). | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 4676 | 12504 | minor | |
| 2781 | public boolean paramsLacking() { return pkixParams.getAnyPolicyInhibited() || pkixParams.getPolicyMappingInhibited() || pkixParams.isExplicitPolicyRequired() || pkixParams.isPolicyMappingInhibited() || pkixParams.isAnyPolicyInhibited() || !pkixParams.getPolicyQualifiersRejected() || !pkixParams.getInitialPolicies().isEmpty(); } YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Primitive obsession 5. Inappropriate intimacy 6. Inconsistent naming 7. Temporary field 8. Comments 9. Shotgun surgery 10. Lazy class 11. Data class 12. Data clumps 13. Speculative generality 14. Message chains 15. Brain overload 16. Large class 17. Deficient encapsulation 18. Combinatorial explosion 19. Extensive coupling 20. Divergent change 21. Inappropriate subclass 22. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method 2 Feature envy 3 Duplicate code 4 Primitive obsession 5 Inappropriate intimacy 6 Inconsistent naming 7 Temporary field 8 Comments 9 Shotgun surgery | t | f | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2781 | 1122 | major | ||
| 387 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 387 | 3944 | critical | |
| 34 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 742 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 34 | 742 | major | |
| 1473 | { "response": "YES I found bad smells", "detected_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiSpinnerUI extends SpinnerUI { /** * The vector containing the real UIs. This is populated * in the call to createUI, and can be obtained by calling * the getUIs method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector<>(); //////////////////// // Common UI methods //////////////////// /** * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. * * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SpinnerUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** * Invokes the contains method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = uis.elementAt(0).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).contains(a,b,c); } return returnValue; } /** * Invokes the update method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).update(a,b); } } /** * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. * * @param a the component to create the UI for * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { MultiSpinnerUI mui = new MultiSpinnerUI(); return MultiLookAndFeel.createUIs(mui, mui.uis, a); } /** * Invokes the installUI method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).installUI(a); } } /** * Invokes the uninstallUI method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).uninstallUI(a); } } /** * Invokes the paint method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { uis.elementAt(i).paint(a,b); } } /** * Invokes the getPreferredSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getPreferredSize(a); } return returnValue; } /** * Invokes the getMinimumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMinimumSize(a); } return returnValue; } /** * Invokes the getMaximumSize method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = uis.elementAt(0).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getMaximumSize(a); } return returnValue; } /** * Invokes the getAccessibleChildrenCount method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = uis.elementAt(0).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChildrenCount(a); } return returnValue; } /** * Invokes the getAccessibleChild method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default LookAndFeel */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = uis.elementAt(0).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { uis.elementAt(i).getAccessibleChild(a,b); } return returnValue; } } |
blob | blob, long method | t | t | t | long method | 0 | 11053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java/#L43-L214 | 1 | 1473 | 11053 | minor | |
| 1595 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Poor variable and method naming 4. Unnecessary commenting 5. Use of instanceof 6. Nested if/else blocks 7. Lack of proper comparison "strategy" 8. Unnecessary casting 9. Lack of clear separation of tasks/responsibilities 10. Possible code duplication 11. Missing error handling 12. Potential for null pointer exceptions 13. Lack of use of standard equals() method 14. Excessive amount of code wrapping | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method 2 Feature envy 3 Poor variable and method naming 4 Unnecessary commenting 5 Use of instanceof 6 Nested if/else blocks 7 Lack of proper comparison "strategy" 8 Unnecessary casting 9 Lack of clear separation of tasks/responsibilities | t | f | t | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 1595 | 11408 | minor | ||
| 2159 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | data class | t | t | t | 0 | 13318 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 1 | 2159 | 13318 | critical | ||
| 772 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 772 | 7285 | major | ||
| 727 | { "message": "YES I found bad smells the bad smells are:", "bad_smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BucketList implements Iterable> { private final ArrayList> bucketList; private final List> immutableVisibleList; private BucketList(ArrayList> bucketList, ArrayList> publicBucketList) { this.bucketList = bucketList; int displayIndex = 0; for (Bucket bucket : publicBucketList) { bucket.displayIndex = displayIndex++; } immutableVisibleList = Collections.unmodifiableList(publicBucketList); } private int getBucketCount() { return immutableVisibleList.size(); } private int getBucketIndex(CharSequence name, Collator collatorPrimaryOnly) { // binary search int start = 0; int limit = bucketList.size(); while ((start + 1) < limit) { int i = (start + limit) / 2; Bucket bucket = bucketList.get(i); int nameVsBucket = collatorPrimaryOnly.compare(name, bucket.lowerBoundary); if (nameVsBucket < 0) { limit = i; } else { start = i; } } Bucket bucket = bucketList.get(start); if (bucket.displayBucket != null) { bucket = bucket.displayBucket; } return bucket.displayIndex; } /** * Private iterator over all the buckets, visible and invisible */ private Iterator> fullIterator() { return bucketList.iterator(); } /** * Iterator over just the visible buckets. */ @Override public Iterator> iterator() { return immutableVisibleList.iterator(); // use immutable list to prevent remove(). } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 6852 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/AlphabeticIndex.java/#L1101-L1154 | 1 | 727 | 6852 | minor | |
| 351 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | 1. long method | t | t | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 351 | 3600 | major | ||
| 2070 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 2070 | 13017 | minor | ||
| 1108 | {"answer": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TableAliasImpl extends SQLSyntaxElementBase implements TableAlias { private final String _tableAlias; private final ColumnNameList _columnAliases; public TableAliasImpl( SQLProcessorAggregator processor, String tableAlias, ColumnNameList columnNames ) { this( processor, TableAlias.class, tableAlias, columnNames ); } protected TableAliasImpl( SQLProcessorAggregator processor, Class implementingClass, String tableAlias, ColumnNameList columnNames ) { super( processor, implementingClass ); Objects.requireNonNull( tableAlias, "table alias table name" ); this._tableAlias = tableAlias; this._columnAliases = columnNames; } public ColumnNameList getColumnAliases() { return this._columnAliases; } public String getTableAlias() { return this._tableAlias; } @Override protected boolean doesEqual( TableAlias another ) { return this._tableAlias.equals( another.getTableAlias() ) && bothNullOrEquals( this._columnAliases, another.getColumnAliases() ); } } |
data class | data class, long method | t | t | t | long method | 0 | 9882 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/grammar/query/TableAliasImpl.java/#L31-L68 | 1 | 1108 | 9882 | minor | |
| 345 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 1 | 345 | 3519 | minor |
| 82 | { "message": "YES, I found bad smells", "bad smells are": ["Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean visitObjectReference(final Pointer objRef, boolean compressed) { return visitObjectReferenceInline(objRef, 0, compressed); } |
feature envy | feature envy | t | t | t | 0 | 1195 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.core.genscavenge/src/com/oracle/svm/core/genscavenge/GreyToBlackObjRefVisitor.java/#L61-L64 | 2 | 82 | 1195 | minor | ||
| 991 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | data class | t | t | t | 0 | 9033 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 1 | 991 | 9033 | minor | ||
| 79 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private final static class DuplicatableProgressTrackingInputStream extends ProgressTrackingInputStream implements DuplicatableInputStream { private DuplicatableProgressTrackingInputStream( final InputStream source, final ProgressTracker progressTracker) { super(source, progressTracker); if (!(source instanceof DuplicatableInputStream)) { throw new IllegalStateException("Source MUST be a DuplicatableInputStream"); } } /** * The progress tracking input stream resulting from this call will re-use the progress tracker from the parent * progress tracking input stream after resetting it, thus invalidating the progress tracked by the parent * stream until now. To ensure correctness of the progress tracking functionality, do NOT read from the parent * stream after duplicating from it. * @return The duplicated progress tracking input stream. */ @Override public InputStream duplicate() { return ProgressTrackingInputStreamFactory.create( ((DuplicatableInputStream) getSource()).duplicate(), getProgressTracker().reset()); } } |
data class | long method, data class | t | t | t | long method | 0 | 1169 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-extensions/src/main/java/com/oracle/bmc/objectstorage/transfer/ProgressTrackingInputStreamFactory.java/#L95-L120 | 1 | 79 | 1169 | minor | |
| 3855 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class MouseObservationEvent extends ObservationEvent { private int deltaX; private int deltaY; private int deltaZ; public MouseObservationEvent(int deltaX, int deltaY, int deltaZ) { super(); this.deltaX = deltaX; this.deltaY = deltaY; this.deltaZ = deltaZ; } @Override public JsonObject getJSON() { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("time", this.timestamp); jsonEvent.addProperty("type", "mouse"); jsonEvent.addProperty("deltaX", this.deltaX); jsonEvent.addProperty("deltaY", this.deltaY); jsonEvent.addProperty("deltaZ", this.deltaZ); return jsonEvent; } } |
data class | long method, data class | t | t | t | long method | 0 | 10011 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/ObservationFromHumanImplementation.java/#L29-L54 | 1 | 3855 | 10011 | minor | |
| 2652 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2652 | 15177 | major | ||
| 1978 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 12631 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 1978 | 12631 | major | ||
| 2257 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Deeply nested code, 6 Inconsistent formatting, 7 Coupling, 8 Lava flow code, 9 Cognitive complexity | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Deeply nested code, 6. Inconsistent formatting, 7. Coupling, 8. Lava flow code, 9. Cognitive complexity. | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 2257 | 13693 | major | |
| 1093 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XelatexRunner extends LatexRunner { /** * Create a new ProgramRunner. */ public XelatexRunner() { super(); } protected String getWindowsProgramName() { return "xelatex.exe"; } protected String getUnixProgramName() { return "xelatex"; } public String getDescription() { return "XeLatex program"; } /** * Enable SyncTeX */ public String getDefaultArguments() { return "-synctex=1 "+super.getDefaultArguments(); } /** * @return output file format (pdf) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_PDF; } } |
data class | data class | t | t | t | 0 | 9748 | https://github.com/eclipse/texlipse/blob/1bc72f856d4144ad0bc9baaa9575457bd7b68e1a/org.eclipse.texlipse/source/org/eclipse/texlipse/builder/XelatexRunner.java/#L20-L55 | 1 | 1093 | 9748 | critical | ||
| 409 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | 1. data class | t | t | t | 0 | 4159 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 409 | 4159 | critical | ||
| 5773 | {"response":"YES I found bad smells","bad smells are:":"1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5773 | 14885 | minor |
| 5337 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | blob, long method | t | t | t | long method | 0 | 15001 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 1 | 5337 | 15001 | minor | |
| 1528 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 1528 | 11199 | minor | |
| 123 | {"message": "YES I found bad smells, the bad smells are: 1. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public QMUIAlphaImageButton addRightImageButton(int drawableResId, int viewId) { return mTopBar.addRightImageButton(drawableResId, viewId); } |
feature envy | 1. feature envy | t | t | t | 0 | 1542 | https://github.com/Tencent/QMUI_Android/blob/6ff5493a05845918c126cce8a3e639f8d996481b/qmui/src/main/java/com/qmuiteam/qmui/widget/QMUITopBarLayout.java/#L136-L138 | 1 | 123 | 1542 | major | ||
| 1173 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1173 | 10199 | minor | ||
| 517 | { "message": "YES I found bad smells", "badSmells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | long method | t | t | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 1 | 517 | 5350 | minor | ||
| 118 | { "response": "YES I found bad smells", "detected_code_smells": { "the_bad_smells_are": [ "Long method", "Feature envy" ] } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @NonNull public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } |
feature envy | the_bad_smells_are: long method, feature envy | t | t | t | the_bad_smells_are: long method | 0 | 1509 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java/#L426-L430 | 2 | 118 | 1509 | critical | |
| 4086 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 4086 | 10775 | major | ||
| 4232 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | long method | t | t | t | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 4232 | 11137 | critical | ||
| 2176 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class | t | t | t | 0 | 13404 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 2176 | 13404 | minor | ||
| 3962 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | data class | t | t | t | 0 | 10380 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 3962 | 10380 | critical | ||
| 1544 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long Method | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1544 | 11245 | minor | ||
| 2519 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 2519 | 14706 | major | |
| 1282 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1282 | 10603 | minor | ||
| 749 | { "answer": "YES I found bad smells", "detected_bad_smells": "the bad smells are: 1. Blob, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({"unchecked", "rawtypes"}) public final class None extends Option { private static final None INSTANCE = new None<>(); /** * Get the static instance. * @param The type of this no-value object. * @return the static instance */ public static final None getInstance() { return INSTANCE; } /** * Default constructor, does nothing. */ public None() { // super(null); // no-op } @Override public boolean hasValue() { return false; } @Override public T getValue() { throw new NoSuchElementException("None does not contain a value"); } @Override public String toString() { return "None()"; } @Override public boolean equals(Object other) { return (other == null || other.getClass() != None.class) ? false : true; } @Override public int hashCode() { return -31; } } |
data class | the bad smells are: 1. blob, 2. data class | t | t | t | the bad smells are: 1. blob | 0 | 7022 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/core/src/org/apache/pivot/functional/monad/None.java/#L24-L70 | 1 | 749 | 7022 | minor | |
| 227 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonDeserialize(using = AggregationsDeserializer.class) static class Aggregations implements Iterable { private final List aggregations; private Map aggregationsAsMap; Aggregations(List aggregations) { this.aggregations = Objects.requireNonNull(aggregations, "aggregations"); } /** * Iterates over the {@link Aggregation}s. */ @Override public final Iterator iterator() { return asList().iterator(); } /** * The list of {@link Aggregation}s. */ final List asList() { return Collections.unmodifiableList(aggregations); } /** * Returns the {@link Aggregation}s keyed by aggregation name. Lazy init. */ final Map asMap() { if (aggregationsAsMap == null) { Map map = new LinkedHashMap<>(aggregations.size()); for (Aggregation aggregation : aggregations) { map.put(aggregation.getName(), aggregation); } this.aggregationsAsMap = unmodifiableMap(map); } return aggregationsAsMap; } /** * Returns the aggregation that is associated with the specified name. */ @SuppressWarnings("unchecked") public final A get(String name) { return (A) asMap().get(name); } @Override public final boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return aggregations.equals(((Aggregations) obj).aggregations); } @Override public final int hashCode() { return Objects.hash(getClass(), aggregations); } } |
data class | data class | t | t | t | 0 | 2450 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/elasticsearch/src/main/java/org/apache/calcite/adapter/elasticsearch/ElasticsearchJson.java/#L390-L447 | 1 | 227 | 2450 | major | ||
| 745 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 745 | 7007 | critical | |
| 919 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8258 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 2 | 919 | 8258 | major | ||
| 767 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 767 | 7227 | major | ||
| 549 | YES I found bad smells the bad smells are: 1. Data class 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Data class2 Feature envy | t | f | t | 0 | 5558 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 2 | 549 | 5558 | major | ||
| 35 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | 1. long method | t | t | t | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 35 | 743 | minor | ||
| 732 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 732 | 6885 | major | ||
| 1716 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long Method | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1716 | 11781 | major | ||
| 2387 | {"response": "YES I found bad smells. the bad smells are: 1. Blob, 2. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | 1. blob, 2. long method | t | t | t | 1. blob | 0 | 14351 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2387 | 14351 | minor | |
| 1352 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method | t | t | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1352 | 10761 | minor | ||
| 2391 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 2391 | 14362 | minor | ||
| 783 | {"response": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | long method | t | t | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 1 | 783 | 7493 | minor | ||
| 787 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 2 | 787 | 7509 | minor | ||
| 1072 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | 1. data class | t | t | t | 0 | 9608 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 1 | 1072 | 9608 | major | ||
| 2547 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14792 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 2547 | 14792 | minor | ||
| 1958 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetaDataFactoryImpl extends EFactoryImpl implements MetaDataFactory { /** * Creates the default factory implementation. * * * @generated */ public static MetaDataFactory init() { try { MetaDataFactory theMetaDataFactory = (MetaDataFactory)EPackage.Registry.INSTANCE.getEFactory(MetaDataPackage.eNS_URI); if (theMetaDataFactory != null) { return theMetaDataFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new MetaDataFactoryImpl(); } /** * Creates an instance of the factory. * * * @generated */ public MetaDataFactoryImpl() { super(); } /** * * * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case MetaDataPackage.MD_MODEL: return createMdModel(); case MetaDataPackage.MD_BUNDLE: return createMdBundle(); case MetaDataPackage.MD_BUNDLE_MEMBER: return createMdBundleMember(); case MetaDataPackage.MD_GROUP_OR_OPTION: return createMdGroupOrOption(); case MetaDataPackage.MD_GROUP: return createMdGroup(); case MetaDataPackage.MD_OPTION: return createMdOption(); case MetaDataPackage.MD_OPTION_DEPENDENCY: return createMdOptionDependency(); case MetaDataPackage.MD_ALGORITHM: return createMdAlgorithm(); case MetaDataPackage.MD_CATEGORY: return createMdCategory(); case MetaDataPackage.MD_OPTION_SUPPORT: return createMdOptionSupport(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return createMdOptionTargetTypeFromString(eDataType, initialValue); case MetaDataPackage.MD_GRAPH_FEATURE: return createMdGraphFeatureFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case MetaDataPackage.MD_OPTION_TARGET_TYPE: return convertMdOptionTargetTypeToString(eDataType, instanceValue); case MetaDataPackage.MD_GRAPH_FEATURE: return convertMdGraphFeatureToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * * * @generated */ public MdModel createMdModel() { MdModelImpl mdModel = new MdModelImpl(); return mdModel; } /** * * * @generated */ public MdBundle createMdBundle() { MdBundleImpl mdBundle = new MdBundleImpl(); return mdBundle; } /** * * * @generated */ public MdBundleMember createMdBundleMember() { MdBundleMemberImpl mdBundleMember = new MdBundleMemberImpl(); return mdBundleMember; } /** * * * @generated */ public MdGroupOrOption createMdGroupOrOption() { MdGroupOrOptionImpl mdGroupOrOption = new MdGroupOrOptionImpl(); return mdGroupOrOption; } /** * * * @generated */ public MdGroup createMdGroup() { MdGroupImpl mdGroup = new MdGroupImpl(); return mdGroup; } /** * * * @generated */ public MdOption createMdOption() { MdOptionImpl mdOption = new MdOptionImpl(); return mdOption; } /** * * * @generated */ public MdOptionDependency createMdOptionDependency() { MdOptionDependencyImpl mdOptionDependency = new MdOptionDependencyImpl(); return mdOptionDependency; } /** * * * @generated */ public MdAlgorithm createMdAlgorithm() { MdAlgorithmImpl mdAlgorithm = new MdAlgorithmImpl(); return mdAlgorithm; } /** * * * @generated */ public MdCategory createMdCategory() { MdCategoryImpl mdCategory = new MdCategoryImpl(); return mdCategory; } /** * * * @generated */ public MdOptionSupport createMdOptionSupport() { MdOptionSupportImpl mdOptionSupport = new MdOptionSupportImpl(); return mdOptionSupport; } /** * * * @generated */ public MdOptionTargetType createMdOptionTargetTypeFromString(EDataType eDataType, String initialValue) { MdOptionTargetType result = MdOptionTargetType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdOptionTargetTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MdGraphFeature createMdGraphFeatureFromString(EDataType eDataType, String initialValue) { MdGraphFeature result = MdGraphFeature.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * * * @generated */ public String convertMdGraphFeatureToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * * * @generated */ public MetaDataPackage getMetaDataPackage() { return (MetaDataPackage)getEPackage(); } /** * * * @deprecated * @generated */ @Deprecated public static MetaDataPackage getPackage() { return MetaDataPackage.eINSTANCE; } } //MetaDataFactoryImpl |
blob | blob, long method | t | t | t | long method | 0 | 12570 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta/src-gen/org/eclipse/elk/core/meta/metaData/impl/MetaDataFactoryImpl.java/#L32-L307 | 1 | 1958 | 12570 | minor | |
| 2260 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 2260 | 13711 | minor | |
| 1694 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | 'Long Method' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,'} | {',L,o,n,g," ",M,h,o,d,'} | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1694 | 11718 | minor |
| 1225 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1: long method | t | t | t | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 1225 | 10351 | minor | ||
| 1409 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | data class | t | t | t | 0 | 10897 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 1409 | 10897 | minor | ||
| 2099 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13157 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 2099 | 13157 | minor | ||
| 627 | { "response": "YES I found bad smells", "detected_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 6267 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 1 | 627 | 6267 | minor | |
| 2418 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14426 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 2 | 2418 | 14426 | minor | ||
| 1779 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Data class", "Message chain", "Data clumps", "Primitive obsession", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | long method, data class, message chain, data clumps, primitive obsession, feature envy | t | t | t | long method, message chain, data clumps, primitive obsession, feature envy | 0 | 11959 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 2 | 1779 | 11959 | critical | |
| 469 | YES I found bad smells" YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 469 | 4555 | major | ||
| 861 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 861 | 7903 | minor | ||
| 2309 | YES, I found bad smells the bad smells are: 1.Long method, 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2Duplicated code, 3Magic number, 4Inappropriate comments, 5Lazy class, 6Feature envy | t | f | t | 2.Duplicated code, 3.Magic number, 4.Inappropriate comments, 5.Lazy class, 6.Feature envy | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2309 | 14095 | minor | |
| 269 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | data class | t | t | t | 0 | 2890 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 269 | 2890 | minor | ||
| 1004 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | 1. long method | t | t | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 1004 | 9254 | major | ||
| 2011 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method, 2Feature envy, 3Magic number, 4Multiple nested if statements, 5Use of a mixture of data types without clear reason, 6Inconsistent indentation, 7Duplicate code, 8Missing comments, 9Poor error handling | t | f | t | 2.Feature envy, 3.Magic number, 4.Multiple nested if statements, 5.Use of a mixture of data types without clear reason, 6.Inconsistent indentation, 7.Duplicate code, 8.Missing comments, 9.Poor error handling. | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2011 | 12750 | critical | |
| 2052 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, data class | t | t | t | long method | 0 | 12902 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 2052 | 12902 | minor | |
| 1123 | {"answer": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class, long method | t | t | t | long method | 0 | 9994 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 1123 | 9994 | critical | |
| 633 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6294 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 633 | 6294 | minor | ||
| 884 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 884 | 8035 | minor | |
| 1941 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. data class | t | t | f | data class | 0 | 12485 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 1941 | 12485 | minor | |
| 2696 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2696 | 15319 | minor | ||
| 2467 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final int v1; final int v2; ModifierOp(int type, int v1, int v2) { super(type); this.v1 = v1; this.v2 = v2; } int getData() { return this.v1; } int getData2() { return this.v2; } } // ================================================================ |
data class | data class | t | t | t | 0 | 14568 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/Op.java/#L204-L218 | 1 | 2467 | 14568 | major | ||
| 747 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 747 | 7016 | minor | ||
| 1744 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long Method | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 1744 | 11849 | major | ||
| 2006 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 2006 | 12721 | major | ||
| 1317 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10691 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1317 | 10691 | minor | |
| 1778 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | blob, long method | t | t | t | long method | 0 | 11958 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 1778 | 11958 | major | |
| 1033 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | long method | t | t | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1033 | 9391 | minor | ||
| 1116 | { "output": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Data class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 9954 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 1 | 1116 | 9954 | major | |
| 911 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are:", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | the bad smells are:, data class | t | t | t | the bad smells are: | 0 | 8224 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 911 | 8224 | critical | |
| 1604 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1604 | 11442 | minor | |
| 2138 | after setting up and validating the experiment. * * * * @param airavataExperiment * @return The Experiment * @throws org.apache.airavata.registry.api.exception.RegistryServiceException */APPLICATION_LOGIC, YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 2138 | 13259 | major | ||
| 1724 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | Long Method, Blob, Data Class | t | f | t | Long Method, Blob | 0 | 11803 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 1724 | 11803 | minor | |
| 366 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 366 | 3740 | minor |
| 1595 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11408 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 1595 | 11408 | minor | |
| 1450 | { "message": "YES I found bad smells", "detected_bad_smells": { "1. Data Class" : "2. Long Method" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable public static final class Result { /** Outcome categories for individual DN lines. */ public enum Outcome { OK, WARNING, ERROR } private final int code; private final String description; private final Outcome outcome; private Result(int code, String description) { this.code = code; this.description = description; if (2000 <= code && code <= 2099) { this.outcome = Outcome.OK; } else if (3500 <= code && code <= 3699) { this.outcome = Outcome.WARNING; } else if (4500 <= code && code <= 4699) { this.outcome = Outcome.ERROR; } else { throw new IllegalArgumentException("Invalid DN result code: " + code); } } public int getCode() { return code; } public String getDescription() { return description; } public Outcome getOutcome() { return outcome; } @Override public String toString() { return toStringHelper(this) .add("code", code) .add("outcome", outcome) .add("description", description) .toString(); } } |
data class | 1. data class: 2. long method | t | t | t | 0 | 10993 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/tmch/LordnLog.java/#L45-L89 | 1 | 1450 | 10993 | minor | ||
| 2049 | {"answer":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class","Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultHotSpotLoweringProvider extends DefaultJavaLoweringProvider implements HotSpotLoweringProvider { protected final HotSpotGraalRuntimeProvider runtime; protected final HotSpotRegistersProvider registers; protected final HotSpotConstantReflectionProvider constantReflection; protected InstanceOfSnippets.Templates instanceofSnippets; protected NewObjectSnippets.Templates newObjectSnippets; protected MonitorSnippets.Templates monitorSnippets; protected WriteBarrierSnippets.Templates writeBarrierSnippets; protected LoadExceptionObjectSnippets.Templates exceptionObjectSnippets; protected UnsafeLoadSnippets.Templates unsafeLoadSnippets; protected AssertionSnippets.Templates assertionSnippets; protected ArrayCopySnippets.Templates arraycopySnippets; protected StringToBytesSnippets.Templates stringToBytesSnippets; protected HashCodeSnippets.Templates hashCodeSnippets; protected ResolveConstantSnippets.Templates resolveConstantSnippets; protected ProfileSnippets.Templates profileSnippets; protected ObjectCloneSnippets.Templates objectCloneSnippets; protected ForeignCallSnippets.Templates foreignCallSnippets; public DefaultHotSpotLoweringProvider(HotSpotGraalRuntimeProvider runtime, MetaAccessProvider metaAccess, ForeignCallsProvider foreignCalls, HotSpotRegistersProvider registers, HotSpotConstantReflectionProvider constantReflection, TargetDescription target) { super(metaAccess, foreignCalls, target, runtime.getVMConfig().useCompressedOops); this.runtime = runtime; this.registers = registers; this.constantReflection = constantReflection; } @Override public void initialize(OptionValues options, Iterable factories, HotSpotProviders providers, GraalHotSpotVMConfig config) { super.initialize(options, factories, runtime, providers, providers.getSnippetReflection()); assert target == providers.getCodeCache().getTarget(); instanceofSnippets = new InstanceOfSnippets.Templates(options, factories, runtime, providers, target); newObjectSnippets = new NewObjectSnippets.Templates(options, factories, runtime, providers, target, config); monitorSnippets = new MonitorSnippets.Templates(options, factories, runtime, providers, target, config.useFastLocking); writeBarrierSnippets = new WriteBarrierSnippets.Templates(options, factories, runtime, providers, target, config); exceptionObjectSnippets = new LoadExceptionObjectSnippets.Templates(options, factories, providers, target); unsafeLoadSnippets = new UnsafeLoadSnippets.Templates(options, factories, providers, target); assertionSnippets = new AssertionSnippets.Templates(options, factories, providers, target); arraycopySnippets = new ArrayCopySnippets.Templates(new HotSpotArraycopySnippets(), options, factories, runtime, providers, providers.getSnippetReflection(), target); stringToBytesSnippets = new StringToBytesSnippets.Templates(options, factories, providers, target); hashCodeSnippets = new HashCodeSnippets.Templates(options, factories, providers, target); resolveConstantSnippets = new ResolveConstantSnippets.Templates(options, factories, providers, target); if (!JavaVersionUtil.Java8OrEarlier) { profileSnippets = new ProfileSnippets.Templates(options, factories, providers, target); } objectCloneSnippets = new ObjectCloneSnippets.Templates(options, factories, providers, target); foreignCallSnippets = new ForeignCallSnippets.Templates(options, factories, providers, target); } public MonitorSnippets.Templates getMonitorSnippets() { return monitorSnippets; } @Override @SuppressWarnings("try") public void lower(Node n, LoweringTool tool) { StructuredGraph graph = (StructuredGraph) n.graph(); try (DebugCloseable context = n.withNodeSourcePosition()) { if (n instanceof Invoke) { lowerInvoke((Invoke) n, tool, graph); } else if (n instanceof LoadMethodNode) { lowerLoadMethodNode((LoadMethodNode) n); } else if (n instanceof GetClassNode) { lowerGetClassNode((GetClassNode) n, tool, graph); } else if (n instanceof StoreHubNode) { lowerStoreHubNode((StoreHubNode) n, graph); } else if (n instanceof OSRStartNode) { lowerOSRStartNode((OSRStartNode) n); } else if (n instanceof BytecodeExceptionNode) { lowerBytecodeExceptionNode((BytecodeExceptionNode) n); } else if (n instanceof InstanceOfNode) { InstanceOfNode instanceOfNode = (InstanceOfNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfNode, tool); } else { if (instanceOfNode.allowsNull()) { ValueNode object = instanceOfNode.getValue(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs(InstanceOfNode.create(instanceOfNode.type(), object, instanceOfNode.profile(), instanceOfNode.getAnchor())); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfNode.replaceAndDelete(newNode); } } } else if (n instanceof InstanceOfDynamicNode) { InstanceOfDynamicNode instanceOfDynamicNode = (InstanceOfDynamicNode) n; if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower(instanceOfDynamicNode, tool); } else { ValueNode mirror = instanceOfDynamicNode.getMirrorOrHub(); if (mirror.stamp(NodeView.DEFAULT).getStackKind() == JavaKind.Object) { ClassGetHubNode classGetHub = graph.unique(new ClassGetHubNode(mirror)); instanceOfDynamicNode.setMirror(classGetHub); } if (instanceOfDynamicNode.allowsNull()) { ValueNode object = instanceOfDynamicNode.getObject(); LogicNode newTypeCheck = graph.addOrUniqueWithInputs( InstanceOfDynamicNode.create(graph.getAssumptions(), tool.getConstantReflection(), instanceOfDynamicNode.getMirrorOrHub(), object, false)); LogicNode newNode = LogicNode.or(graph.unique(IsNullNode.create(object)), newTypeCheck, GraalDirectives.UNLIKELY_PROBABILITY); instanceOfDynamicNode.replaceAndDelete(newNode); } } } else if (n instanceof ClassIsAssignableFromNode) { if (graph.getGuardsStage().areDeoptsFixed()) { instanceofSnippets.lower((ClassIsAssignableFromNode) n, tool); } } else if (n instanceof NewInstanceNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewInstanceNode) n, registers, tool); } } else if (n instanceof DynamicNewInstanceNode) { DynamicNewInstanceNode newInstanceNode = (DynamicNewInstanceNode) n; if (newInstanceNode.getClassClass() == null) { JavaConstant classClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(Class.class)); ConstantNode classClass = ConstantNode.forConstant(classClassMirror, tool.getMetaAccess(), graph); newInstanceNode.setClassClass(classClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(newInstanceNode, registers, tool); } } else if (n instanceof NewArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewArrayNode) n, registers, tool); } } else if (n instanceof DynamicNewArrayNode) { DynamicNewArrayNode dynamicNewArrayNode = (DynamicNewArrayNode) n; if (dynamicNewArrayNode.getVoidClass() == null) { JavaConstant voidClassMirror = constantReflection.asJavaClass(metaAccess.lookupJavaType(void.class)); ConstantNode voidClass = ConstantNode.forConstant(voidClassMirror, tool.getMetaAccess(), graph); dynamicNewArrayNode.setVoidClass(voidClass); } if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower(dynamicNewArrayNode, registers, tool); } } else if (n instanceof VerifyHeapNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((VerifyHeapNode) n, registers, tool); } } else if (n instanceof RawMonitorEnterNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((RawMonitorEnterNode) n, registers, tool); } } else if (n instanceof MonitorExitNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { monitorSnippets.lower((MonitorExitNode) n, registers, tool); } } else if (n instanceof ArrayCopyNode) { arraycopySnippets.lower((ArrayCopyNode) n, tool); } else if (n instanceof ArrayCopyWithSlowPathNode) { arraycopySnippets.lower((ArrayCopyWithSlowPathNode) n, tool); } else if (n instanceof G1PreWriteBarrier) { writeBarrierSnippets.lower((G1PreWriteBarrier) n, registers, tool); } else if (n instanceof G1PostWriteBarrier) { writeBarrierSnippets.lower((G1PostWriteBarrier) n, registers, tool); } else if (n instanceof G1ReferentFieldReadBarrier) { writeBarrierSnippets.lower((G1ReferentFieldReadBarrier) n, registers, tool); } else if (n instanceof SerialWriteBarrier) { writeBarrierSnippets.lower((SerialWriteBarrier) n, tool); } else if (n instanceof SerialArrayRangeWriteBarrier) { writeBarrierSnippets.lower((SerialArrayRangeWriteBarrier) n, tool); } else if (n instanceof G1ArrayRangePreWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePreWriteBarrier) n, registers, tool); } else if (n instanceof G1ArrayRangePostWriteBarrier) { writeBarrierSnippets.lower((G1ArrayRangePostWriteBarrier) n, registers, tool); } else if (n instanceof NewMultiArrayNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { newObjectSnippets.lower((NewMultiArrayNode) n, tool); } } else if (n instanceof LoadExceptionObjectNode) { exceptionObjectSnippets.lower((LoadExceptionObjectNode) n, registers, tool); } else if (n instanceof AssertionNode) { assertionSnippets.lower((AssertionNode) n, tool); } else if (n instanceof StringToBytesNode) { if (graph.getGuardsStage().areDeoptsFixed()) { stringToBytesSnippets.lower((StringToBytesNode) n, tool); } } else if (n instanceof IntegerDivRemNode) { // Nothing to do for division nodes. The HotSpot signal handler catches divisions by // zero and the MIN_VALUE / -1 cases. } else if (n instanceof AbstractDeoptimizeNode || n instanceof UnwindNode || n instanceof RemNode || n instanceof SafepointNode) { /* No lowering, we generate LIR directly for these nodes. */ } else if (n instanceof ClassGetHubNode) { lowerClassGetHubNode((ClassGetHubNode) n, tool); } else if (n instanceof HubGetClassNode) { lowerHubGetClassNode((HubGetClassNode) n, tool); } else if (n instanceof KlassLayoutHelperNode) { lowerKlassLayoutHelperNode((KlassLayoutHelperNode) n, tool); } else if (n instanceof ComputeObjectAddressNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { lowerComputeObjectAddressNode((ComputeObjectAddressNode) n); } } else if (n instanceof IdentityHashCodeNode) { hashCodeSnippets.lower((IdentityHashCodeNode) n, tool); } else if (n instanceof ResolveDynamicConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveDynamicConstantNode) n, tool); } } else if (n instanceof ResolveConstantNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveConstantNode) n, tool); } } else if (n instanceof ResolveMethodAndLoadCountersNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((ResolveMethodAndLoadCountersNode) n, tool); } } else if (n instanceof InitializeKlassNode) { if (graph.getGuardsStage().areFrameStatesAtDeopts()) { resolveConstantSnippets.lower((InitializeKlassNode) n, tool); } } else if (n instanceof ProfileNode) { profileSnippets.lower((ProfileNode) n, tool); } else { super.lower(n, tool); } } } private static void lowerComputeObjectAddressNode(ComputeObjectAddressNode n) { /* * Lower the node into a ComputeObjectAddress node and an Add but ensure that it's below any * potential safepoints and above it's uses. */ for (Node use : n.usages().snapshot()) { if (use instanceof FixedNode) { FixedNode fixed = (FixedNode) use; StructuredGraph graph = n.graph(); GetObjectAddressNode address = graph.add(new GetObjectAddressNode(n.getObject())); graph.addBeforeFixed(fixed, address); AddNode add = graph.addOrUnique(new AddNode(address, n.getOffset())); use.replaceFirstInput(n, add); } else { throw GraalError.shouldNotReachHere("Unexpected floating use of ComputeObjectAddressNode " + n); } } GraphUtil.unlinkFixedNode(n); n.safeDelete(); } private void lowerKlassLayoutHelperNode(KlassLayoutHelperNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getHub().isConstant(); AddressNode address = createOffsetAddress(graph, n.getHub(), runtime.getVMConfig().klassLayoutHelperOffset); n.replaceAtUsagesAndDelete(graph.unique(new FloatingReadNode(address, KLASS_LAYOUT_HELPER_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE))); } private void lowerHubGetClassNode(HubGetClassNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } ValueNode hub = n.getHub(); GraalHotSpotVMConfig vmConfig = runtime.getVMConfig(); StructuredGraph graph = n.graph(); assert !hub.isConstant() || GraalOptions.ImmutableCode.getValue(graph.getOptions()); AddressNode mirrorAddress = createOffsetAddress(graph, hub, vmConfig.classMirrorOffset); FloatingReadNode read = graph.unique( new FloatingReadNode(mirrorAddress, CLASS_MIRROR_LOCATION, null, vmConfig.classMirrorIsHandle ? StampFactory.forKind(target.wordJavaKind) : n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); if (vmConfig.classMirrorIsHandle) { AddressNode address = createOffsetAddress(graph, read, 0); read = graph.unique(new FloatingReadNode(address, CLASS_MIRROR_HANDLE_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); } n.replaceAtUsagesAndDelete(read); } private void lowerClassGetHubNode(ClassGetHubNode n, LoweringTool tool) { if (tool.getLoweringStage() == LoweringTool.StandardLoweringStage.HIGH_TIER) { return; } StructuredGraph graph = n.graph(); assert !n.getValue().isConstant(); AddressNode address = createOffsetAddress(graph, n.getValue(), runtime.getVMConfig().klassOffset); FloatingReadNode read = graph.unique(new FloatingReadNode(address, CLASS_KLASS_LOCATION, null, n.stamp(NodeView.DEFAULT), null, BarrierType.NONE)); n.replaceAtUsagesAndDelete(read); } private void lowerInvoke(Invoke invoke, LoweringTool tool, StructuredGraph graph) { if (invoke.callTarget() instanceof MethodCallTargetNode) { MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget(); NodeInputList parameters = callTarget.arguments(); ValueNode receiver = parameters.size() <= 0 ? null : parameters.get(0); if (!callTarget.isStatic() && receiver.stamp(NodeView.DEFAULT) instanceof ObjectStamp && !StampTool.isPointerNonNull(receiver)) { ValueNode nonNullReceiver = createNullCheckedValue(receiver, invoke.asNode(), tool); parameters.set(0, nonNullReceiver); receiver = nonNullReceiver; } JavaType[] signature = callTarget.targetMethod().getSignature().toParameterTypes(callTarget.isStatic() ? null : callTarget.targetMethod().getDeclaringClass()); LoweredCallTargetNode loweredCallTarget = null; OptionValues options = graph.getOptions(); if (InlineVTableStubs.getValue(options) && callTarget.invokeKind().isIndirect() && (AlwaysInlineVTableStubs.getValue(options) || invoke.isPolymorphic())) { HotSpotResolvedJavaMethod hsMethod = (HotSpotResolvedJavaMethod) callTarget.targetMethod(); ResolvedJavaType receiverType = invoke.getReceiverType(); if (hsMethod.isInVirtualMethodTable(receiverType)) { JavaKind wordKind = runtime.getTarget().wordJavaKind; ValueNode hub = createReadHub(graph, receiver, tool); ReadNode metaspaceMethod = createReadVirtualMethod(graph, hub, hsMethod, receiverType); // We use LocationNode.ANY_LOCATION for the reads that access the // compiled code entry as HotSpot does not guarantee they are final // values. int methodCompiledEntryOffset = runtime.getVMConfig().methodCompiledEntryOffset; AddressNode address = createOffsetAddress(graph, metaspaceMethod, methodCompiledEntryOffset); ReadNode compiledEntry = graph.add(new ReadNode(address, any(), StampFactory.forKind(wordKind), BarrierType.NONE)); loweredCallTarget = graph.add(new HotSpotIndirectCallTargetNode(metaspaceMethod, compiledEntry, parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); graph.addBeforeFixed(invoke.asNode(), metaspaceMethod); graph.addAfterFixed(metaspaceMethod, compiledEntry); } } if (loweredCallTarget == null) { loweredCallTarget = graph.add(new HotSpotDirectCallTargetNode(parameters.toArray(new ValueNode[parameters.size()]), callTarget.returnStamp(), signature, callTarget.targetMethod(), HotSpotCallingConventionType.JavaCall, callTarget.invokeKind())); } callTarget.replaceAndDelete(loweredCallTarget); } } private CompressEncoding getOopEncoding() { return runtime.getVMConfig().getOopEncoding(); } @Override protected Stamp loadCompressedStamp(ObjectStamp stamp) { return HotSpotNarrowOopStamp.compressed(stamp, getOopEncoding()); } @Override protected ValueNode newCompressionNode(CompressionOp op, ValueNode value) { return new HotSpotCompressionNode(op, value, getOopEncoding()); } @Override public ValueNode staticFieldBase(StructuredGraph graph, ResolvedJavaField f) { HotSpotResolvedJavaField field = (HotSpotResolvedJavaField) f; JavaConstant base = constantReflection.asJavaClass(field.getDeclaringClass()); return ConstantNode.forConstant(base, metaAccess, graph); } @Override protected ValueNode createReadArrayComponentHub(StructuredGraph graph, ValueNode arrayHub, FixedNode anchor) { /* * Anchor the read of the element klass to the cfg, because it is only valid when arrayClass * is an object class, which might not be the case in other parts of the compiled method. */ AddressNode address = createOffsetAddress(graph, arrayHub, runtime.getVMConfig().arrayClassElementOffset); return graph.unique(new FloatingReadNode(address, OBJ_ARRAY_KLASS_ELEMENT_KLASS_LOCATION, null, KlassPointerStamp.klassNonNull(), AbstractBeginNode.prevBegin(anchor))); } @Override protected void lowerUnsafeLoadNode(RawLoadNode load, LoweringTool tool) { StructuredGraph graph = load.graph(); if (!(load instanceof GuardedUnsafeLoadNode) && !graph.getGuardsStage().allowsFloatingGuards() && addReadBarrier(load)) { unsafeLoadSnippets.lower(load, tool); } else { super.lowerUnsafeLoadNode(load, tool); } } private void lowerLoadMethodNode(LoadMethodNode loadMethodNode) { StructuredGraph graph = loadMethodNode.graph(); HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) loadMethodNode.getMethod(); ReadNode metaspaceMethod = createReadVirtualMethod(graph, loadMethodNode.getHub(), method, loadMethodNode.getReceiverType()); graph.replaceFixed(loadMethodNode, metaspaceMethod); } private static void lowerGetClassNode(GetClassNode getClass, LoweringTool tool, StructuredGraph graph) { StampProvider stampProvider = tool.getStampProvider(); LoadHubNode hub = graph.unique(new LoadHubNode(stampProvider, getClass.getObject())); HubGetClassNode hubGetClass = graph.unique(new HubGetClassNode(tool.getMetaAccess(), hub)); getClass.replaceAtUsagesAndDelete(hubGetClass); hub.lower(tool); hubGetClass.lower(tool); } private void lowerStoreHubNode(StoreHubNode storeHub, StructuredGraph graph) { WriteNode hub = createWriteHub(graph, storeHub.getObject(), storeHub.getValue()); graph.replaceFixed(storeHub, hub); } @Override public BarrierType fieldInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.IMPRECISE : BarrierType.NONE; } @Override public BarrierType arrayInitializationBarrier(JavaKind entryKind) { return (entryKind == JavaKind.Object && !runtime.getVMConfig().useDeferredInitBarriers) ? BarrierType.PRECISE : BarrierType.NONE; } private void lowerOSRStartNode(OSRStartNode osrStart) { StructuredGraph graph = osrStart.graph(); if (graph.getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { StartNode newStart = graph.add(new StartNode()); ParameterNode buffer = graph.addWithoutUnique(new ParameterNode(0, StampPair.createSingle(StampFactory.forKind(runtime.getTarget().wordJavaKind)))); ForeignCallNode migrationEnd = graph.add(new ForeignCallNode(foreignCalls, OSR_MIGRATION_END, buffer)); migrationEnd.setStateAfter(osrStart.stateAfter()); newStart.setNext(migrationEnd); FixedNode next = osrStart.next(); osrStart.setNext(null); migrationEnd.setNext(next); graph.setStart(newStart); final int wordSize = target.wordSize; // @formatter:off // taken from c2 locals_addr = osr_buf + (max_locals-1)*wordSize) // @formatter:on int localsOffset = (graph.method().getMaxLocals() - 1) * wordSize; for (OSRLocalNode osrLocal : graph.getNodes(OSRLocalNode.TYPE)) { int size = osrLocal.getStackKind().getSlotCount(); int offset = localsOffset - (osrLocal.index() + size - 1) * wordSize; AddressNode address = createOffsetAddress(graph, buffer, offset); ReadNode load = graph.add(new ReadNode(address, any(), osrLocal.stamp(NodeView.DEFAULT), BarrierType.NONE)); osrLocal.replaceAndDelete(load); graph.addBeforeFixed(migrationEnd, load); } // @formatter:off // taken from c2 monitors_addr = osr_buf + (max_locals+mcnt*2-1)*wordSize); // @formatter:on final int lockCount = osrStart.stateAfter().locksSize(); final int locksOffset = (graph.method().getMaxLocals() + lockCount * 2 - 1) * wordSize; // first initialize the lock slots for all enters with the displaced marks read from the // buffer for (OSRMonitorEnterNode osrMonitorEnter : graph.getNodes(OSRMonitorEnterNode.TYPE)) { MonitorIdNode monitorID = osrMonitorEnter.getMonitorId(); OSRLockNode lock = (OSRLockNode) osrMonitorEnter.object(); final int index = lock.index(); final int offsetDisplacedHeader = locksOffset - ((index * 2) + 1) * wordSize; final int offsetLockObject = locksOffset - index * 2 * wordSize; // load the displaced mark from the osr buffer AddressNode addressDisplacedHeader = createOffsetAddress(graph, buffer, offsetDisplacedHeader); ReadNode loadDisplacedHeader = graph.add(new ReadNode(addressDisplacedHeader, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, loadDisplacedHeader); // we need to initialize the stack slot for the lock BeginLockScopeNode beginLockScope = graph.add(new BeginLockScopeNode(lock.getStackKind(), monitorID.getLockDepth())); graph.addBeforeFixed(migrationEnd, beginLockScope); // write the displaced mark to the correct stack slot AddressNode addressDisplacedMark = createOffsetAddress(graph, beginLockScope, runtime.getVMConfig().basicLockDisplacedHeaderOffset); WriteNode writeStackSlot = graph.add(new WriteNode(addressDisplacedMark, DISPLACED_MARK_WORD_LOCATION, loadDisplacedHeader, BarrierType.NONE)); graph.addBeforeFixed(migrationEnd, writeStackSlot); // load the lock object from the osr buffer AddressNode addressLockObject = createOffsetAddress(graph, buffer, offsetLockObject); ReadNode loadObject = graph.add(new ReadNode(addressLockObject, any(), lock.stamp(NodeView.DEFAULT), BarrierType.NONE)); lock.replaceAndDelete(loadObject); graph.addBeforeFixed(migrationEnd, loadObject); } osrStart.replaceAtUsagesAndDelete(newStart); } } static final class Exceptions { protected static final EnumMap cachedExceptions; static { cachedExceptions = new EnumMap<>(BytecodeExceptionKind.class); cachedExceptions.put(BytecodeExceptionKind.NULL_POINTER, clearStackTrace(new NullPointerException())); cachedExceptions.put(BytecodeExceptionKind.OUT_OF_BOUNDS, clearStackTrace(new ArrayIndexOutOfBoundsException())); cachedExceptions.put(BytecodeExceptionKind.CLASS_CAST, clearStackTrace(new ClassCastException())); cachedExceptions.put(BytecodeExceptionKind.ARRAY_STORE, clearStackTrace(new ArrayStoreException())); cachedExceptions.put(BytecodeExceptionKind.DIVISION_BY_ZERO, clearStackTrace(new ArithmeticException())); } private static RuntimeException clearStackTrace(RuntimeException ex) { ex.setStackTrace(new StackTraceElement[0]); return ex; } } public static final class RuntimeCalls { public static final EnumMap runtimeCalls; static { runtimeCalls = new EnumMap<>(BytecodeExceptionKind.class); runtimeCalls.put(BytecodeExceptionKind.ARRAY_STORE, new ForeignCallDescriptor("createArrayStoreException", ArrayStoreException.class, Object.class)); runtimeCalls.put(BytecodeExceptionKind.CLASS_CAST, new ForeignCallDescriptor("createClassCastException", ClassCastException.class, Object.class, KlassPointer.class)); runtimeCalls.put(BytecodeExceptionKind.NULL_POINTER, new ForeignCallDescriptor("createNullPointerException", NullPointerException.class)); runtimeCalls.put(BytecodeExceptionKind.OUT_OF_BOUNDS, new ForeignCallDescriptor("createOutOfBoundsException", ArrayIndexOutOfBoundsException.class, int.class, int.class)); runtimeCalls.put(BytecodeExceptionKind.DIVISION_BY_ZERO, new ForeignCallDescriptor("createDivisionByZeroException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW, new ForeignCallDescriptor("createIntegerExactOverflowException", ArithmeticException.class)); runtimeCalls.put(BytecodeExceptionKind.LONG_EXACT_OVERFLOW, new ForeignCallDescriptor("createLongExactOverflowException", ArithmeticException.class)); } } private void throwCachedException(BytecodeExceptionNode node) { if (IS_IN_NATIVE_IMAGE) { throw new InternalError("Can't throw exception from SVM object"); } Throwable exception = Exceptions.cachedExceptions.get(node.getExceptionKind()); assert exception != null; StructuredGraph graph = node.graph(); FloatingNode exceptionNode = ConstantNode.forConstant(constantReflection.forObject(exception), metaAccess, graph); graph.replaceFixedWithFloating(node, exceptionNode); } private void lowerBytecodeExceptionNode(BytecodeExceptionNode node) { if (OmitHotExceptionStacktrace.getValue(node.getOptions())) { throwCachedException(node); return; } ForeignCallDescriptor descriptor = RuntimeCalls.runtimeCalls.get(node.getExceptionKind()); assert descriptor != null; StructuredGraph graph = node.graph(); ForeignCallNode foreignCallNode = graph.add(new ForeignCallNode(foreignCalls, descriptor, node.stamp(NodeView.DEFAULT), node.getArguments())); graph.replaceFixedWithFixed(node, foreignCallNode); } private boolean addReadBarrier(RawLoadNode load) { if (runtime.getVMConfig().useG1GC && load.graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS && load.object().getStackKind() == JavaKind.Object && load.accessKind() == JavaKind.Object && !StampTool.isPointerAlwaysNull(load.object())) { ResolvedJavaType type = StampTool.typeOrNull(load.object()); if (type != null && !type.isArray()) { return true; } } return false; } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, HotSpotResolvedJavaMethod method, ResolvedJavaType receiverType) { return createReadVirtualMethod(graph, hub, method.vtableEntryOffset(receiverType)); } private ReadNode createReadVirtualMethod(StructuredGraph graph, ValueNode hub, int vtableEntryOffset) { assert vtableEntryOffset > 0; // We use LocationNode.ANY_LOCATION for the reads that access the vtable // entry as HotSpot does not guarantee that this is a final value. Stamp methodStamp = MethodPointerStamp.methodNonNull(); AddressNode address = createOffsetAddress(graph, hub, vtableEntryOffset); ReadNode metaspaceMethod = graph.add(new ReadNode(address, any(), methodStamp, BarrierType.NONE)); return metaspaceMethod; } @Override protected ValueNode createReadHub(StructuredGraph graph, ValueNode object, LoweringTool tool) { if (tool.getLoweringStage() != LoweringTool.StandardLoweringStage.LOW_TIER) { return graph.unique(new LoadHubNode(tool.getStampProvider(), object)); } assert !object.isConstant() || object.isNullConstant(); KlassPointerStamp hubStamp = KlassPointerStamp.klassNonNull(); if (runtime.getVMConfig().useCompressedClassPointers) { hubStamp = hubStamp.compressed(runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); LocationIdentity hubLocation = runtime.getVMConfig().useCompressedClassPointers ? COMPRESSED_HUB_LOCATION : HUB_LOCATION; FloatingReadNode memoryRead = graph.unique(new FloatingReadNode(address, hubLocation, null, hubStamp, null, BarrierType.NONE)); if (runtime.getVMConfig().useCompressedClassPointers) { return HotSpotCompressionNode.uncompress(memoryRead, runtime.getVMConfig().getKlassEncoding()); } else { return memoryRead; } } private WriteNode createWriteHub(StructuredGraph graph, ValueNode object, ValueNode value) { assert !object.isConstant() || object.asConstant().isDefaultForKind(); ValueNode writeValue = value; if (runtime.getVMConfig().useCompressedClassPointers) { writeValue = HotSpotCompressionNode.compress(value, runtime.getVMConfig().getKlassEncoding()); } AddressNode address = createOffsetAddress(graph, object, runtime.getVMConfig().hubOffset); return graph.add(new WriteNode(address, HUB_WRITE_LOCATION, writeValue, BarrierType.NONE)); } @Override protected BarrierType fieldLoadBarrierType(ResolvedJavaField f) { HotSpotResolvedJavaField loadField = (HotSpotResolvedJavaField) f; BarrierType barrierType = BarrierType.NONE; if (runtime.getVMConfig().useG1GC && loadField.getJavaKind() == JavaKind.Object && metaAccess.lookupJavaType(Reference.class).equals(loadField.getDeclaringClass()) && loadField.getName().equals("referent")) { barrierType = BarrierType.PRECISE; } return barrierType; } @Override public int fieldOffset(ResolvedJavaField f) { return f.getOffset(); } @Override public int arrayLengthOffset() { return runtime.getVMConfig().arrayOopDescLengthOffset(); } @Override protected final JavaKind getStorageKind(ResolvedJavaField field) { return field.getJavaKind(); } @Override public ObjectCloneSnippets.Templates getObjectCloneSnippets() { return objectCloneSnippets; } @Override public ForeignCallSnippets.Templates getForeignCallSnippets() { return foreignCallSnippets; } } |
blob | long method, data class, blob | t | t | t | long method, data class | 0 | 12883 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/meta/DefaultHotSpotLoweringProvider.java/#L184-L809 | 1 | 2049 | 12883 | minor | |
| 2439 | { "answer": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 14478 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 1 | 2439 | 14478 | major | |
| 73 | { "message": "YES, I found bad smells", "the bad smells are": [ "1. Long class", "2. Long method", "3. Feature envy", "4. Data class", "5. Message chains", "6. Shotgun surgery", "7. Comments", "8. Data clumps" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | 1. long class, 2. long method, 3. feature envy, 4. data class, 5. message chains, 6. shotgun surgery, 7. comments, 8. data clumps | t | t | t | 1. long class, 2. long method, 3. feature envy, 5. message chains, 6. shotgun surgery, 7. comments, 8. data clumps | 0 | 1109 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 2 | 73 | 1109 | minor | |
| 1901 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 1901 | 12362 | major |
| 3912 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 3912 | 10243 | minor | ||
| 1567 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | long method, data class | t | t | t | long method | 0 | 11329 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 1567 | 11329 | minor | |
| 2604 | LFOAbstractType YES I found bad smells the bad smells are: 1.Long method 2.Inappropriate intimacy 3.Magic Number 4.Missing comments 5.Inappropriate abbreviation 6.Bad naming 7.Dead Code 8.Data class 9.Feature envy 10.Incomplete comments 11.Missing final modifier 12.Tradition over Efficiency 13.Confusing naming 14.Large class 15.Lazy Class 16.Magic String 17.Refused bequest 18.Repeated switch 19.Variable length signal 20.Long method chain 21.Speculative Generality 22.Inappropriate type 23.Flat hierarchy 24.Nested method 25.Feature toggle 26.Lazy initialization 27.Method chain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | Long method2Inappropriate intimacy3Magic Number4Missing comments5Inappropriate abbreviation6Bad naming7Dead Code8Data class9Feature envy | t | f | t | 0 | 15026 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 2 | 2604 | 15026 | major | ||
| 2498 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14649 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 1 | 2498 | 14649 | minor | ||
| 2342 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 2342 | 14179 | major | ||
| 2028 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 12806 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 2028 | 12806 | major | ||
| 795 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | long method | t | t | t | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 1 | 795 | 7555 | minor | ||
| 2107 | { "response": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | 1. long method, 2. data class | t | t | f | 1. long method | data class | 0 | 13177 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 2107 | 13177 | minor |
| 1673 | { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 11642 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 1673 | 11642 | major | |
| 38 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { if (kapuaEvent == null) { //service bus error. Throw some exception? } LOG.info("GroupService: received kapua event from {}, operation {}", kapuaEvent.getService(), kapuaEvent.getOperation()); if ("account".equals(kapuaEvent.getService()) && "delete".equals(kapuaEvent.getOperation())) { deleteGroupByAccountId(kapuaEvent.getScopeId(), kapuaEvent.getEntityId()); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 761 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java/#L203-L212 | 2 | 38 | 761 | major | |
| 1718 | { "message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11785 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 1718 | 11785 | minor | |
| 2450 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2450 | 14505 | minor | |
| 1041 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | long method | t | t | t | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1041 | 9429 | minor | ||
| 2235 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13609 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 2 | 2235 | 13609 | minor | ||
| 295 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 295 | 3109 | minor | ||
| 2074 | { "message": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13036 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 1 | 2074 | 13036 | major | |
| 1661 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetAgent extends Agent { //---------------------navigational members----------------------------------- // All these request objects point to the same physical request object. ConnectionRequestInterface connectionRequest_; StatementRequestInterface statementRequest_; ResultSetRequestInterface resultSetRequest_; // All these reply objects point to the same physical reply object. ConnectionReply connectionReply_; private ConnectionReply packageReply_; StatementReply statementReply_; ResultSetReply resultSetReply_; //---------------------navigational cheat-links------------------------------- // Cheat-links are for convenience only, and are not part of the conceptual model. // Warning: // Cheat-links should only be defined for invariant state data. // That is, the state data is set by the constructor and never changes. // Alias for (NetConnection) super.connection NetConnection netConnection_; // Alias for (Request) super.*Request, all in one // In the case of the NET implementation, these all point to the same physical request object. private Request request_; NetConnectionRequest netConnectionRequest_; private NetPackageRequest netPackageRequest_; private NetStatementRequest netStatementRequest_; private NetResultSetRequest netResultSetRequest_; // Alias for (Reply) super.*Reply, all in one. // In the case of the NET implementation, these all point to the same physical reply object. private Reply reply_; NetConnectionReply netConnectionReply_; private NetPackageReply netPackageReply_; private NetStatementReply netStatementReply_; private NetResultSetReply netResultSetReply_; //-----------------------------state------------------------------------------ Socket socket_; private InputStream rawSocketInputStream_; private OutputStream rawSocketOutputStream_; String server_; int port_; private int clientSSLMode_; private EbcdicCcsidManager ebcdicCcsidManager_; private Utf8CcsidManager utf8CcsidManager_; private CcsidManager currentCcsidManager_; // TODO: Remove target? Keep just one CcsidManager? //public CcsidManager targetCcsidManager_; Typdef typdef_; Typdef targetTypdef_; Typdef originalTargetTypdef_; // added to support typdef overrides private int svrcod_; int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7; int targetSqlam_ = orignalTargetSqlam_; SqlException exceptionOpeningSocket_ = null; SqlException exceptionConvertingRdbnam = null; /** * Flag which indicates that a writeChain has been started and data sent to * the server. * If true, starting a new write chain will throw a DisconnectException. * It is cleared when the write chain is ended. */ private boolean writeChainIsDirty_ = false; //---------------------constructors/finalizer--------------------------------- // Only used for testing public NetAgent(NetConnection netConnection, LogWriter logWriter) throws SqlException { super(netConnection, logWriter); this.netConnection_ = netConnection; } NetAgent(NetConnection netConnection, LogWriter netLogWriter, int loginTimeout, String server, int port, int clientSSLMode) throws SqlException { super(netConnection, netLogWriter); server_ = server; port_ = port; netConnection_ = netConnection; clientSSLMode_ = clientSSLMode; if (server_ == null) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET), "serverName"); } try { socket_ = (Socket)AccessController.doPrivileged( new OpenSocketAction(server, port, clientSSLMode_)); } catch (PrivilegedActionException e) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER), e.getException(), e.getException().getClass().getName(), server, port, e.getException().getMessage()); } // Set TCP/IP Socket Properties try { if (exceptionOpeningSocket_ == null) { socket_.setTcpNoDelay(true); // disables nagles algorithm socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2 socket_.setSoTimeout(loginTimeout * 1000); } } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION), e, e.getMessage()); } try { if (exceptionOpeningSocket_ == null) { rawSocketOutputStream_ = socket_.getOutputStream(); rawSocketInputStream_ = socket_.getInputStream(); } } catch (IOException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM), e, e.getMessage()); } ebcdicCcsidManager_ = new EbcdicCcsidManager(); utf8CcsidManager_ = new Utf8CcsidManager(); currentCcsidManager_ = ebcdicCcsidManager_; if (netConnection_.isXAConnection()) { NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_); netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_; netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, netConnection_.commBufferSize_); netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_; netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } else { netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_); netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; netResultSetRequest_ = new NetResultSetRequest(this, netConnection_.commBufferSize_); netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } } protected void resetAgent_(LogWriter netLogWriter, //CcsidManager sourceCcsidManager, //CcsidManager targetCcsidManager, int loginTimeout, String server, int port) throws SqlException { exceptionConvertingRdbnam = null; // most properties will remain unchanged on connect reset. targetTypdef_ = originalTargetTypdef_; svrcod_ = 0; // Set TCP/IP Socket Properties try { socket_.setSoTimeout(loginTimeout * 1000); } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } throw new SqlException(logWriter_, new ClientMessageId(SQLState.SOCKET_EXCEPTION), e, e.getMessage()); } } void setSvrcod(int svrcod) { if (svrcod > svrcod_) { svrcod_ = svrcod; } } void clearSvrcod() { svrcod_ = CodePoint.SVRCOD_INFO; } private int getSvrcod() { return svrcod_; } public void flush_() throws DisconnectException { sendRequest(); reply_.initialize(); } // Close socket and its streams. public void close_() throws SqlException { // can we just close the socket here, do we need to close streams individually SqlException accumulatedExceptions = null; if (rawSocketInputStream_ != null) { try { rawSocketInputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes accumulatedExceptions = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); } finally { rawSocketInputStream_ = null; } } if (rawSocketOutputStream_ != null) { try { rawSocketOutputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { rawSocketOutputStream_ = null; } } if (socket_ != null) { try { socket_.close(); } catch (IOException e) { // again {6} = 0, indicates the socket was closed. // maybe set {4} to e.getMessage(). // do this for now and but may need to modify or // add this to the message pubs. SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { socket_ = null; } } if (accumulatedExceptions != null) { throw accumulatedExceptions; } } /** * Specifies the maximum blocking time that should be used when sending * and receiving messages. The timeout is implemented by using the the * underlying socket implementation's timeout support. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @param timeout The timeout value in seconds. A value of 0 corresponds to * infinite timeout. */ protected void setTimeout(int timeout) { try { // Sets a timeout on the socket socket_.setSoTimeout(timeout * 1000); // convert to milliseconds } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.setTimeout: ignoring exception: " + se); } } } /** * Returns the current timeout value that is set on the socket. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @return The timeout value in seconds. A value of 0 corresponds to * that no timeout is specified on the socket. */ protected int getTimeout() { int timeout = 0; // 0 is default timeout for sockets // Read the timeout currently set on the socket try { timeout = socket_.getSoTimeout(); } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.getTimeout: ignoring exception: " + se); } } // Convert from milliseconds to seconds (note that this truncates // the results towards zero but that should not be a problem). timeout = timeout / 1000; return timeout; } private void sendRequest() throws DisconnectException { try { request_.flush(rawSocketOutputStream_); } catch (IOException e) { throwCommunicationsFailure(e); } } public InputStream getInputStream() { return rawSocketInputStream_; } public CcsidManager getCurrentCcsidManager() { return currentCcsidManager_; } public OutputStream getOutputStream() { return rawSocketOutputStream_; } void setInputStream(InputStream inputStream) { rawSocketInputStream_ = inputStream; } void setOutputStream(OutputStream outputStream) { rawSocketOutputStream_ = outputStream; } void throwCommunicationsFailure(Throwable cause) throws DisconnectException { //DisconnectException //accumulateReadExceptionAndDisconnect // note when {6} = 0 it indicates the socket was closed. // need to still validate any token values against message publications. accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(this, new ClientMessageId(SQLState.COMMUNICATION_ERROR), cause, cause.getMessage())); } // ----------------------- call-down methods --------------------------------- protected void markChainBreakingException_() { setSvrcod(CodePoint.SVRCOD_ERROR); } public void checkForChainBreakingException_() throws SqlException { int svrcod = getSvrcod(); clearSvrcod(); if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker { super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one. } } private void writeDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.writeDeferredReset(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } /** * Marks the agent's write chain as dirty. A write chain is dirty when data * from it has been sent to the server. A dirty write chain cannot be reset * and reused for another request until the remaining data has been sent to * the server and the write chain properly ended. * * Resetting a dirty chain will cause the new request to be appended to the * unfinished request already at the server, which will likely lead to * cryptic syntax errors. */ void markWriteChainAsDirty() { writeChainIsDirty_ = true; } private void verifyWriteChainIsClean() throws DisconnectException { if (writeChainIsDirty_) { throw new DisconnectException(this, new ClientMessageId(SQLState.NET_WRITE_CHAIN_IS_DIRTY)); } } public void beginWriteChainOutsideUOW() throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); } public void beginWriteChain(ClientStatement statement) throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); super.beginWriteChain(statement); } protected void endWriteChain() {} private void readDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.readDeferredReset(); checkForExceptions(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } protected void beginReadChain(ClientStatement statement) throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChain(statement); } protected void beginReadChainOutsideUOW() throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChainOutsideUOW(); } /** * Switches the current CCSID manager to UTF-8 */ void switchToUtf8CcsidMgr() { currentCcsidManager_ = utf8CcsidManager_; } /** * Switches the current CCSID manager to EBCDIC */ void switchToEbcdicMgr() { currentCcsidManager_ = ebcdicCcsidManager_; } } |
blob | blob, data class | t | t | t | data class | 0 | 11610 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.client/org/apache/derby/client/net/NetAgent.java/#L43-L550 | 1 | 1661 | 11610 | critical | |
| 962 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8570 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 962 | 8570 | minor | ||
| 2401 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Deeply nested code 4. Excessive use of conditionals and boolean checks 5. Lack of proper naming and code documentation 6. Use of multiple if statements instead of a switch statement or polymorphism 7. Inconsistent indentations and formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Feature envy2 Long method3 Deeply nested code4 Excessive use of conditionals and boolean checks5 Lack of proper naming and code documentation6 Use of multiple if statements instead of a switch statement or polymorphism7 Inconsistent indentations and formatting | t | f | t | 0 | 14380 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 2401 | 14380 | minor | ||
| 3621 | of the detected smells are omitted in the answer YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: None |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L181787-L181806 | 2 | 3621 | 8146 | minor | ||
| 1270 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10566 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1270 | 10566 | major | ||
| 1991 | {"response": "YES I found bad smells", "detected bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1991 | 12682 | major | |
| 73 | {"answer":"YES I found bad smells","detectedBadSmells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | long method, data class | t | t | t | long method | 0 | 1109 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 73 | 1109 | minor | |
| 1406 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | data class, long method | t | t | t | long method | 0 | 10877 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 1 | 1406 | 10877 | minor | |
| 2111 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static long openProcessToken(int access) { try { return OpenProcessToken(GetCurrentProcess(), access); } catch (WindowsException x) { return 0L; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13188 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/windows/classes/sun/nio/fs/WindowsSecurity.java/#L39-L45 | 2 | 2111 | 13188 | minor | ||
| 2196 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChartReportItemHelper { private static ChartReportItemHelper instance = new ChartReportItemHelper( ); protected ChartReportItemHelper( ) { } public static void initInstance( ChartReportItemHelper newInstance ) { instance = newInstance; } public static ChartReportItemHelper instance( ) { return instance; } public CubeHandle getBindingCubeHandle( ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingCube( itemHandle ); } public DataSetHandle getBindingDataSetHandle(ReportItemHandle itemHandle ) { return ChartCubeUtil.getBindingDataSet( itemHandle ); } public boolean checkCubeBindings( ExtendedItemHandle handle, Iterator columnBindings ) { return ChartCubeUtil.checkColumnbindingForCube( columnBindings ); } public ChartExpressionUtil.ExpressionCodec createExpressionCodec( ExtendedItemHandle handle ) { return ChartModelHelper.instance( ).createExpressionCodec( ); } public boolean loadExpression( ExpressionCodec exprCodec, ComputedColumnHandle cch ) { return ChartItemUtil.loadExpression( exprCodec, cch ); } public ComputedColumnHandle findDimensionBinding( ExpressionCodec exprCodec, String dimName, String levelName, Collection bindings, ReportItemHandle itemHandle ) { for ( ComputedColumnHandle cch : bindings ) { ChartReportItemHelper.instance( ).loadExpression( exprCodec, cch ); String[] levelNames = exprCodec.getLevelNames( ); if ( levelNames != null && levelNames[0].equals( dimName ) && levelNames[1].equals( levelName ) ) { return cch; } } return null; } /** * Returns all bindings used by chart. * * @param cm * @param handle * @param validExtensionNames * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle, List validExtensionNames ) { return handle.columnBindingsIterator( ); } /** * Returns all bindings used by chart. * * @param cm * @param handle * @return all bindings used by chart. */ public Iterator getAllUsedBindings( Chart cm, ReportItemHandle handle ) { return handle.columnBindingsIterator( ); } public String getMeasureExprIndicator( CubeHandle cubeHandle ) { return ExpressionUtil.MEASURE_INDICATOR; } public List getLevelBindingNamesOfCrosstab( CrosstabViewHandle viewHandle, ReportItemHandle chartHandle ) { ArrayList names = new ArrayList( ); for ( int i = 0; i < viewHandle.getDimensionCount( ); i++ ) { DimensionViewHandle dimensionHandle = viewHandle.getDimension( i ); dimensionHandle.availableBindings( ); for ( int k = 0; k < dimensionHandle.getLevelCount( ); k++ ) { names.add( dimensionHandle.getLevel( k ) .getCubeLevel( ) .getName( ) ); } } return names; } } |
data class | data class, long method | t | t | t | long method | 0 | 13481 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/api/ChartReportItemHelper.java/#L36-L148 | 1 | 2196 | 13481 | minor | |
| 3786 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Excessive conditional complexity 4. Code duplication 5. Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy3 Excessive conditional complexity4 Code duplication5 Poorly named variables ("this_present_protocol_version" and "that_present_protocol_version") | t | f | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 3786 | 9536 | minor | ||
| 359 | YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
feature envy | Long method 2 Repetitive code 3 Feature envy | t | f | t | 0 | 3692 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 2 | 359 | 3692 | minor | ||
| 369 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 369 | 3819 | major | ||
| 1651 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 1651 | 11579 | minor | |
| 715 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Comments as code 4. Magic numbers 5. Indecent exposure 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method2 Duplicate code3 Comments as code4 Magic numbers5 Indecent exposure6 Feature envy | t | f | t | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 715 | 6821 | major | ||
| 374 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 374 | 3864 | major | ||
| 2585 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class, long method | t | t | t | long method | 0 | 14976 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 2585 | 14976 | major | |
| 1654 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 1654 | 11585 | minor | |
| 2259 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method | t | t | t | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 2259 | 13703 | minor | ||
| 1926 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1926 | 12438 | major | ||
| 1047 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 9457 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1047 | 9457 | minor | |
| 1688 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent indentation 4. Magic numbers 5. Lack of meaningful variable names 6. Inappropriate or excessive use of comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy3 Inconsistent indentation4 Magic numbers5 Lack of meaningful variable names6 Inappropriate or excessive use of comments | t | f | t | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 1688 | 11692 | minor | ||
| 3694 | { "output": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | 1. long method | t | t | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 3694 | 8659 | minor | ||
| 195 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 1 | 195 | 2234 | minor | ||
| 2470 | { "message": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are:", "1. Blob", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | the bad smells are:, 1. blob, 2. data class | t | t | t | the bad smells are:, 1. blob | 0 | 14576 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 1 | 2470 | 14576 | critical | |
| 309 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3204 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 2 | 309 | 3204 | critical | |
| 1262 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1262 | 10513 | critical | ||
| 1298 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method, 2Magic numbers, 3Complex code, 4Duplicated code, 5Exception handling within a loop, 6Use of abbreviations in method name, 7Consider splitting up the method into smaller methods | t | f | t | 2.Magic numbers, 3.Complex code, 4.Duplicated code, 5.Exception handling within a loop, 6.Use of abbreviations in method name, 7.Consider splitting up the method into smaller methods. | 0 | 10639 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 1298 | 10639 | major | |
| 2170 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | data class, long method | t | t | t | long method | 0 | 13356 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 2170 | 13356 | minor | |
| 2707 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | blob, long method | t | t | t | long method | 0 | 15352 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 2707 | 15352 | minor | |
| 527 | {"message": "YES I found bad smells", "bad smells are": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | feature envy | t | t | t | 0 | 5449 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 1 | 527 | 5449 | minor | ||
| 1428 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells_are": [ "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | bad_smells_are: long method | t | t | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 1428 | 10949 | minor | ||
| 1140 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10089 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 2 | 1140 | 10089 | minor | ||
| 2051 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | data class | t | t | t | 0 | 12894 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 1 | 2051 | 12894 | major | ||
| 1363 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 1363 | 10780 | major | |
| 2703 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Duplicate code, 3 Indecent exposure, 4 Inappropriate intimacy, 5 Feature envy | t | f | t | 2. Duplicate code, 3. Indecent exposure, 4. Inappropriate intimacy, 5. Feature envy | 0 | 15335 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 2703 | 15335 | major | |
| 2324 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | data class, long method | t | t | t | long method | 0 | 14136 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 2324 | 14136 | minor | |
| 1018 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Long method 2 Feature Envy | t | f | t | 0 | 9334 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 1018 | 9334 | major | ||
| 834 | LFOAbstractType YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Low cohesion 4. Repeating code 5. Primitive obsession 6.Freeloader class 7.Feature envy 8. Inappropriate visibility modifier 9. Inconsistent naming convention 10. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | Long method2 Data class3 Low cohesion4 Repeating code 5 Primitive obsession 6Freeloader class 7Feature envy 8 Inappropriate visibility modifier 9 Inconsistent naming convention | t | f | t | 0 | 7749 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 2 | 834 | 7749 | major | ||
| 856 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Validator childNodeChanged(String name, NodeState before, NodeState after) throws CommitFailedException { Tree beforeTree = (parentBefore == null) ? null : parentBefore.getChild(name); Tree afterTree = parentAfter.getChild(name); if (isTokenTree(beforeTree) || isTokenTree(afterTree)) { validateTokenTree(afterTree); } else if (isTokensParent(beforeTree) || isTokensParent(afterTree)) { validateTokensParent(afterTree); } return new VisibleValidator(new TokenValidator(beforeTree, afterTree, commitInfo), true, true); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 7885 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-core/src/main/java/org/apache/jackrabbit/oak/security/authentication/token/TokenValidatorProvider.java/#L130-L142 | 1 | 856 | 7885 | major | |
| 2358 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14233 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 2358 | 14233 | major | ||
| 2419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if statement checking for targetType) 4. Null checks 5. Catching throwable instead of specific exception 6. Hardcoding class names and checking for specific class name (String editorName = targetType.getName() + "Editor") 7. Not following naming conventions (targetType instead of targetClass) 8. Use of two return statements within one method (line 10 and line 21) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy3 Duplicate code (in the if statement checking for targetType)4 Null checks5 Catching throwable instead of specific exception6 Hardcoding class names and checking for specific class name (String editorName = targetTypegetName() + "Editor")7 Not following naming conventions (targetType instead of targetClass)8 Use of two return statements within one method (line | t | f | t | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 2419 | 14427 | minor | ||
| 1995 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 1. data class | t | t | f | data class | 0 | 12696 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 1995 | 12696 | minor | |
| 1706 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | data class, long method | t | t | t | long method | 0 | 11754 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 1706 | 11754 | critical | |
| 2703 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | long method, blob | t | t | t | blob | 0 | 15335 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 2703 | 15335 | major | |
| 1447 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | data class, long method | t | t | t | long method | 0 | 10988 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 1447 | 10988 | minor | |
| 4052 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10701 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 4052 | 10701 | minor | |
| 2674 | // 5. Input optimisation YES I found bad smells 1. Long method 2. Unused code (deprecated oldAlgo variable) 3. Duplicate code/feature envy (repetitive use of algoUtils.computeBucketMapJoinCPUCost and algoUtils.computeBucketMapJoinIOCost) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | Long method2 Unused code (deprecated oldAlgo variable)3 Duplicate code/feature envy (repetitive use of algoUtilscomputeBucketMapJoinCPUCost and algoUtilscomputeBucketMapJoinIOCost) | t | f | t | 0 | 15226 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2674 | 15226 | minor | ||
| 1129 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean hasCmpPersistenceUnit(final Persistence persistence) { for (final PersistenceUnit unit : persistence.getPersistenceUnit()) { if (unit.getName().startsWith("cmp")) { return true; } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10016 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/config/OutputGeneratedDescriptors.java/#L173-L180 | 2 | 1129 | 10016 | minor | ||
| 310 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 3205 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 2 | 310 | 3205 | critical | |
| 195 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
long method | 1. long method | t | t | t | 0 | 2234 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 2 | 195 | 2234 | minor | ||
| 2567 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | data class | t | t | t | 0 | 14871 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 1 | 2567 | 14871 | minor | ||
| 2359 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method | t | f | t | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 2359 | 14234 | minor | ||
| 333 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean checkExplicitUserPassword(ManagementContext mgmt, String user, String password) { BrooklynProperties properties = ((ManagementContextInternal)mgmt).getBrooklynProperties(); String expectedPassword = properties.getConfig(BrooklynWebConfig.PASSWORD_FOR_USER(user)); String salt = properties.getConfig(BrooklynWebConfig.SALT_FOR_USER(user)); String expectedSha256 = properties.getConfig(BrooklynWebConfig.SHA256_FOR_USER(user)); return checkPassword(password, expectedPassword, expectedSha256, salt); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 3421 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/rest/rest-server/src/main/java/org/apache/brooklyn/rest/security/provider/ExplicitUsersSecurityProvider.java/#L94-L101 | 2 | 333 | 3421 | minor | ||
| 2141 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | data class, long method | t | t | t | long method | 0 | 13266 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 2141 | 13266 | major | |
| 5180 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
data class | data class, long method | t | t | t | long method | 0 | 14486 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 1 | 5180 | 14486 | minor | |
| 1552 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Nested conditionals 4. Inconsistent variable naming 5. Unused code 6. Inappropriate naming (e.g. delegate, parent) 7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method2 Feature Envy3 Nested conditionals4 Inconsistent variable naming5 Unused code6 Inappropriate naming (eg delegate, parent)7 Complex nested operations 8 Mixed responsibilities (handling XML and DOM implementation separately) | t | f | t | parent)7. Complex nested operations 8. Mixed responsibilities (handling XML and DOM implementation separately) | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 1552 | 11269 | major | |
| 5676 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | long method, feature envy, long parameter list | t | t | t | feature envy, long parameter list | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 2 | 5676 | 11770 | minor | |
| 1046 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | long method, blob | t | t | t | blob | 0 | 9456 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1046 | 9456 | minor | |
| 2203 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 2203 | 13507 | critical | ||
| 876 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
blob | blob, long method | t | t | t | long method | 0 | 8010 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 876 | 8010 | minor | |
| 2280 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | data class | t | t | t | 0 | 13797 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 2280 | 13797 | minor | ||
| 1962 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | long method | t | t | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1962 | 12586 | minor | ||
| 5500 | { "response": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static final Iterator applyAll(final S start, final Traversal.Admin traversal) { traversal.reset(); traversal.addStart(traversal.getTraverserGenerator().generate(start, traversal.getStartStep(), 1l)); return traversal; // flatMap } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 3063 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalUtil.java/#L99-L103 | 2 | 5500 | 3063 | major | |
| 984 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate naming conventions for variables (e.g. "v", "l", "vd") 3. Feature envy (defining a variable in a different class) 4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)") 7. Lack of comments and documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Inappropriate naming conventions for variables (eg "v", "l", "vd")3 Feature envy (defining a variable in a different class)4 Use of unintuitive data types (eg List, Set, VarSymbol) 5 Poor code readability and organization 6 Code duplication (eg "vdvartype = access(vdvartype)")7 Lack of comments and documentation | t | f | t | "l", "vd")3. Feature envy (defining a variable in a different class)4. Use of unintuitive data types (e.g. List, Set, VarSymbol) 5. Poor code readability and organization 6. Code duplication (e.g. "vd.vartype = access(vd.vartype)")7. Lack of comments and documentation. | 0 | 8875 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 984 | 8875 | minor | |
| 2558 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2558 | 14834 | major | |
| 5508 | This is the unfortunate code spaced in the file YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3712 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5508 | 3712 | major | ||
| 1836 | YES I found bad smells The bad smells are: Long method, Inappropriate naming, Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method, Inappropriate naming, Duplicate code | t | f | t | Inappropriate naming, Duplicate code | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 1836 | 12140 | major | |
| 1112 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 9894 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 1 | 1112 | 9894 | minor | ||
| 1063 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1063 | 9551 | minor | ||
| 970 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 970 | 8695 | minor | ||
| 2633 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 2633 | 15109 | minor | ||
| 1315 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | 1: data class | t | t | t | 0 | 10688 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 1315 | 10688 | critical | ||
| 2453 | { "output": "YES I found bad smells. the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | 1. data class | t | t | t | 0 | 14518 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 1 | 2453 | 14518 | minor | ||
| 2534 | {"message": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | data class, long method | t | t | t | long method | 0 | 14749 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 2534 | 14749 | major | |
| 3968 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | long method, blob | t | t | t | blob | 0 | 10409 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 3968 | 10409 | critical | |
| 1737 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1737 | 11831 | minor | |
| 2397 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method | t | t | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2397 | 14375 | minor | ||
| 4111 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Data class (lack of encapsulation) 5. Spaghetti code (multiple levels of nesting) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Data class (lack of encapsulation)5 Spaghetti code (multiple levels of nesting) | t | f | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 4111 | 10827 | major | ||
| 2678 | YES, I found bad smells. the bad smells are: 1. Long method 2. Commented out code 3. Useless if statement 4. Duplicated code 5. Inconsistent naming convention (camelCase and lowercase) 6. Magic number (0 in the if statement) 7. Feature envy (mailToAddresses and mailHost variables are called multiple times) 8. Mixing of responsibilities (sending email and error handling in the same method) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Commented out code3 Useless if statement4 Duplicated code5 Inconsistent naming convention (camelCase and lowercase)6 Magic number (0 in the if statement)7 Feature envy (mailToAddresses and mailHost variables are called multiple times)8 Mixing of responsibilities (sending email and error handling in the same method) | t | f | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2678 | 15253 | minor | ||
| 2387 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14351 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2387 | 14351 | minor | ||
| 960 | YES I found bad smells - Long method, Feature envy: the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 960 | 8567 | minor | ||
| 5490 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy"] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5490 | 1877 | minor |
| 2670 | public class CodeChecker { YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2 Feature envy | t | f | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2670 | 15211 | major | ||
| 1934 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method | t | f | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 1934 | 12462 | major | ||
| 973 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8773 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 973 | 8773 | minor | ||
| 1659 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | 1 Data Class | t | f | t | 0 | 11607 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 1659 | 11607 | minor | ||
| 1882 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | long method | t | t | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 1882 | 12288 | minor | ||
| 2197 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 2 | 2197 | 13483 | minor | ||
| 447 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | 1. data class | t | t | f | data class | 0 | 4364 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 447 | 4364 | critical | |
| 2097 | YES, I found bad smells. the bad smells are: 1. Long class 2. Long method 3. Feature envy 4. Inconsistent naming conventions 5. Unnecessary comments 6. Data class 7. Frequent use of conditional statements and null checks 8. Complex and convoluted code logic 9. Violation of Liskov substitution principle (subclass Map4 does not strictly adhere to the behavior of its superclass Map3) 10. Use of raw types (set of raw type AbstractSet is used without specifying its generic type) 11. Violation of single responsibility principle (Map4 class handles both map data structure and internal iterator logic) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
data class | Long class2 Long method3 Feature envy4 Inconsistent naming conventions5 Unnecessary comments6 Data class7 Frequent use of conditional statements and null checks8 Complex and convoluted code logic9 Violation of Liskov substitution principle (subclass Map4 does not strictly adhere to the behavior of its superclass Map3) | t | f | t | 0 | 13149 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 2 | 2097 | 13149 | minor | ||
| 2463 | COMMENT Sheyi, this is not Java code. But I've still included my feedback below. YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 2463 | 14551 | major | ||
| 1070 | {"result":"YES I found bad smells","the bad smells are":["1. Long Method","2. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class WindmillStateReader { /** * Ideal maximum bytes in a TagBag response. However, Windmill will always return at least one * value if possible irrespective of this limit. */ public static final long MAX_BAG_BYTES = 8L << 20; // 8MB /** * Ideal maximum bytes in a KeyedGetDataResponse. However, Windmill will always return at least * one value if possible irrespective of this limit. */ public static final long MAX_KEY_BYTES = 16L << 20; // 16MB /** * When combined with a key and computationId, represents the unique address for state managed by * Windmill. */ private static class StateTag { private enum Kind { VALUE, BAG, WATERMARK; } private final Kind kind; private final ByteString tag; private final String stateFamily; /** * For {@link Kind#BAG} kinds: A previous 'continuation_position' returned by Windmill to signal * the resulting bag was incomplete. Sending that position will request the next page of values. * Null for first request. * * Null for other kinds. */ @Nullable private final Long requestPosition; private StateTag( Kind kind, ByteString tag, String stateFamily, @Nullable Long requestPosition) { this.kind = kind; this.tag = tag; this.stateFamily = Preconditions.checkNotNull(stateFamily); this.requestPosition = requestPosition; } private StateTag(Kind kind, ByteString tag, String stateFamily) { this(kind, tag, stateFamily, null); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof StateTag)) { return false; } StateTag that = (StateTag) obj; return Objects.equal(this.kind, that.kind) && Objects.equal(this.tag, that.tag) && Objects.equal(this.stateFamily, that.stateFamily) && Objects.equal(this.requestPosition, that.requestPosition); } @Override public int hashCode() { return Objects.hashCode(kind, tag, stateFamily, requestPosition); } @Override public String toString() { return "Tag(" + kind + "," + tag.toStringUtf8() + "," + stateFamily + (requestPosition == null ? "" : ("," + requestPosition.toString())) + ")"; } } /** * An in-memory collection of deserialized values and an optional continuation position to pass to * Windmill when fetching the next page of values. */ private static class ValuesAndContPosition { private final List values; /** Position to pass to next request for next page of values. Null if done. */ @Nullable private final Long continuationPosition; public ValuesAndContPosition(List values, @Nullable Long continuationPosition) { this.values = values; this.continuationPosition = continuationPosition; } } private final String computation; private final ByteString key; private final long shardingKey; private final long workToken; private final MetricTrackingWindmillServerStub server; private long bytesRead = 0L; public WindmillStateReader( MetricTrackingWindmillServerStub server, String computation, ByteString key, long shardingKey, long workToken) { this.server = server; this.computation = computation; this.key = key; this.shardingKey = shardingKey; this.workToken = workToken; } private static final class CoderAndFuture { private Coder coder; private final SettableFuture future; private CoderAndFuture(Coder coder, SettableFuture future) { this.coder = coder; this.future = future; } private SettableFuture getFuture() { return future; } private SettableFuture getNonDoneFuture(StateTag stateTag) { if (future.isDone()) { throw new IllegalStateException("Future for " + stateTag + " is already done"); } return future; } private Coder getAndClearCoder() { if (coder == null) { throw new IllegalStateException("Coder has already been cleared from cache"); } Coder result = coder; coder = null; return result; } private void checkNoCoder() { if (coder != null) { throw new IllegalStateException("Unexpected coder"); } } } @VisibleForTesting ConcurrentLinkedQueue pendingLookups = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap> waiting = new ConcurrentHashMap<>(); private Future stateFuture( StateTag stateTag, @Nullable Coder coder) { CoderAndFuture coderAndFuture = new CoderAndFuture<>(coder, SettableFuture.create()); CoderAndFuture existingCoderAndFutureWildcard = waiting.putIfAbsent(stateTag, coderAndFuture); if (existingCoderAndFutureWildcard == null) { // Schedule a new request. It's response is guaranteed to find the future and coder. pendingLookups.add(stateTag); } else { // Piggy-back on the pending or already answered request. @SuppressWarnings("unchecked") CoderAndFuture existingCoderAndFuture = (CoderAndFuture) existingCoderAndFutureWildcard; coderAndFuture = existingCoderAndFuture; } return wrappedFuture(coderAndFuture.getFuture()); } private CoderAndFuture getWaiting( StateTag stateTag, boolean shouldRemove) { CoderAndFuture coderAndFutureWildcard; if (shouldRemove) { coderAndFutureWildcard = waiting.remove(stateTag); } else { coderAndFutureWildcard = waiting.get(stateTag); } if (coderAndFutureWildcard == null) { throw new IllegalStateException("Missing future for " + stateTag); } @SuppressWarnings("unchecked") CoderAndFuture coderAndFuture = (CoderAndFuture) coderAndFutureWildcard; return coderAndFuture; } public Future watermarkFuture(ByteString encodedTag, String stateFamily) { return stateFuture(new StateTag(StateTag.Kind.WATERMARK, encodedTag, stateFamily), null); } public Future valueFuture(ByteString encodedTag, String stateFamily, Coder coder) { return stateFuture(new StateTag(StateTag.Kind.VALUE, encodedTag, stateFamily), coder); } public Future> bagFuture( ByteString encodedTag, String stateFamily, Coder elemCoder) { // First request has no continuation position. StateTag stateTag = new StateTag(StateTag.Kind.BAG, encodedTag, stateFamily); // Convert the ValuesAndContPosition to Iterable. return valuesToPagingIterableFuture( stateTag, elemCoder, this.>stateFuture(stateTag, elemCoder)); } /** * Internal request to fetch the next 'page' of values in a TagBag. Return null if no continuation * position is in {@code contStateTag}, which signals there are no more pages. */ @Nullable private Future> continuationBagFuture( StateTag contStateTag, Coder elemCoder) { if (contStateTag.requestPosition == null) { // We're done. return null; } return stateFuture(contStateTag, elemCoder); } /** * A future which will trigger a GetData request to Windmill for all outstanding futures on the * first {@link #get}. */ private static class WrappedFuture extends ForwardingFuture.SimpleForwardingFuture { /** * The reader we'll use to service the eventual read. Null if read has been fulfilled. * * NOTE: We must clear this after the read is fulfilled to prevent space leaks. */ @Nullable private WindmillStateReader reader; public WrappedFuture(WindmillStateReader reader, Future delegate) { super(delegate); this.reader = reader; } @Override public T get() throws InterruptedException, ExecutionException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!delegate().isDone() && reader != null) { // Only one thread per reader, so no race here. reader.startBatchAndBlock(); } reader = null; return super.get(timeout, unit); } } private Future wrappedFuture(final Future future) { if (future.isDone()) { // If the underlying lookup is already complete, we don't need to create the wrapper. return future; } else { // Otherwise, wrap the true future so we know when to trigger a GetData. return new WrappedFuture<>(this, future); } } /** Function to extract an {@link Iterable} from the continuation-supporting page read future. */ private static class ToIterableFunction implements Function, Iterable> { /** * Reader to request continuation pages from, or {@literal null} if no continuation pages * required. */ @Nullable private WindmillStateReader reader; private final StateTag stateTag; private final Coder elemCoder; public ToIterableFunction(WindmillStateReader reader, StateTag stateTag, Coder elemCoder) { this.reader = reader; this.stateTag = stateTag; this.elemCoder = elemCoder; } @Override public Iterable apply(ValuesAndContPosition valuesAndContPosition) { if (valuesAndContPosition.continuationPosition == null) { // Number of values is small enough Windmill sent us the entire bag in one response. reader = null; return valuesAndContPosition.values; } else { // Return an iterable which knows how to come back for more. StateTag contStateTag = new StateTag( stateTag.kind, stateTag.tag, stateTag.stateFamily, valuesAndContPosition.continuationPosition); return new BagPagingIterable<>( reader, valuesAndContPosition.values, contStateTag, elemCoder); } } } /** * Return future which transforms a {@code ValuesAndContPosition} result into the initial * Iterable result expected from the external caller. */ private Future> valuesToPagingIterableFuture( final StateTag stateTag, final Coder elemCoder, final Future> future) { return Futures.lazyTransform(future, new ToIterableFunction(this, stateTag, elemCoder)); } public void startBatchAndBlock() { // First, drain work out of the pending lookups into a set. These will be the items we fetch. HashSet toFetch = new HashSet<>(); while (!pendingLookups.isEmpty()) { StateTag stateTag = pendingLookups.poll(); if (stateTag == null) { break; } if (!toFetch.add(stateTag)) { throw new IllegalStateException("Duplicate tags being fetched."); } } // If we failed to drain anything, some other thread pulled it off the queue. We have no work // to do. if (toFetch.isEmpty()) { return; } Windmill.KeyedGetDataRequest request = createRequest(toFetch); Windmill.KeyedGetDataResponse response = server.getStateData(computation, request); if (response == null) { throw new RuntimeException("Windmill unexpectedly returned null for request " + request); } consumeResponse(request, response, toFetch); } public long getBytesRead() { return bytesRead; } private Windmill.KeyedGetDataRequest createRequest(Iterable toFetch) { Windmill.KeyedGetDataRequest.Builder keyedDataBuilder = Windmill.KeyedGetDataRequest.newBuilder() .setKey(key) .setShardingKey(shardingKey) .setWorkToken(workToken); for (StateTag stateTag : toFetch) { switch (stateTag.kind) { case BAG: TagBag.Builder bag = keyedDataBuilder .addBagsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily) .setFetchMaxBytes(MAX_BAG_BYTES); if (stateTag.requestPosition != null) { // We're asking for the next page. bag.setRequestPosition(stateTag.requestPosition); } break; case WATERMARK: keyedDataBuilder .addWatermarkHoldsToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; case VALUE: keyedDataBuilder .addValuesToFetchBuilder() .setTag(stateTag.tag) .setStateFamily(stateTag.stateFamily); break; default: throw new RuntimeException("Unknown kind of tag requested: " + stateTag.kind); } } keyedDataBuilder.setMaxBytes(MAX_KEY_BYTES); return keyedDataBuilder.build(); } private void consumeResponse( Windmill.KeyedGetDataRequest request, Windmill.KeyedGetDataResponse response, Set toFetch) { bytesRead += response.getSerializedSize(); if (response.getFailed()) { // Set up all the futures for this key to throw an exception: KeyTokenInvalidException keyTokenInvalidException = new KeyTokenInvalidException(key.toStringUtf8()); for (StateTag stateTag : toFetch) { waiting.get(stateTag).future.setException(keyTokenInvalidException); } return; } if (!key.equals(response.getKey())) { throw new RuntimeException("Expected data for key " + key + " but was " + response.getKey()); } for (Windmill.TagBag bag : response.getBagsList()) { StateTag stateTag = new StateTag( StateTag.Kind.BAG, bag.getTag(), bag.getStateFamily(), bag.hasRequestPosition() ? bag.getRequestPosition() : null); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeBag(bag, stateTag); } for (Windmill.WatermarkHold hold : response.getWatermarkHoldsList()) { StateTag stateTag = new StateTag(StateTag.Kind.WATERMARK, hold.getTag(), hold.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeWatermark(hold, stateTag); } for (Windmill.TagValue value : response.getValuesList()) { StateTag stateTag = new StateTag(StateTag.Kind.VALUE, value.getTag(), value.getStateFamily()); if (!toFetch.remove(stateTag)) { throw new IllegalStateException( "Received response for unrequested tag " + stateTag + ". Pending tags: " + toFetch); } consumeTagValue(value, stateTag); } if (!toFetch.isEmpty()) { throw new IllegalStateException( "Didn't receive responses for all pending fetches. Missing: " + toFetch); } } @VisibleForTesting static class WeightedList extends ForwardingList implements Weighted { private List delegate; long weight; WeightedList(List delegate) { this.delegate = delegate; this.weight = 0; } @Override protected List delegate() { return delegate; } @Override public boolean add(T elem) { throw new UnsupportedOperationException("Must use AddWeighted()"); } @Override public long getWeight() { return weight; } public void addWeighted(T elem, long weight) { delegate.add(elem); this.weight += weight; } } /** The deserialized values in {@code bag} as a read-only array list. */ private List bagPageValues(TagBag bag, Coder elemCoder) { if (bag.getValuesCount() == 0) { return new WeightedList(Collections.emptyList()); } WeightedList valueList = new WeightedList<>(new ArrayList(bag.getValuesCount())); for (ByteString value : bag.getValuesList()) { try { valueList.addWeighted( elemCoder.decode(value.newInput(), Coder.Context.OUTER), value.size()); } catch (IOException e) { throw new IllegalStateException("Unable to decode tag list using " + elemCoder, e); } } return valueList; } private void consumeBag(TagBag bag, StateTag stateTag) { boolean shouldRemove; if (stateTag.requestPosition == null) { // This is the response for the first page. // Leave the future in the cache so subsequent requests for the first page // can return immediately. shouldRemove = false; } else { // This is a response for a subsequent page. // Don't cache the future since we may need to make multiple requests with different // continuation positions. shouldRemove = true; } CoderAndFuture> coderAndFuture = getWaiting(stateTag, shouldRemove); SettableFuture> future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); List values = this.bagPageValues(bag, coder); future.set( new ValuesAndContPosition( values, bag.hasContinuationPosition() ? bag.getContinuationPosition() : null)); } private void consumeWatermark(Windmill.WatermarkHold watermarkHold, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); // No coders for watermarks coderAndFuture.checkNoCoder(); Instant hold = null; for (long timestamp : watermarkHold.getTimestampsList()) { Instant instant = new Instant(TimeUnit.MICROSECONDS.toMillis(timestamp)); // TIMESTAMP_MAX_VALUE represents infinity, and windmill will return it if no hold is set, so // don't treat it as a hold here. if (instant.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE) && (hold == null || instant.isBefore(hold))) { hold = instant; } } future.set(hold); } private void consumeTagValue(TagValue tagValue, StateTag stateTag) { CoderAndFuture coderAndFuture = getWaiting(stateTag, false); SettableFuture future = coderAndFuture.getNonDoneFuture(stateTag); Coder coder = coderAndFuture.getAndClearCoder(); if (tagValue.hasValue() && tagValue.getValue().hasData() && !tagValue.getValue().getData().isEmpty()) { InputStream inputStream = tagValue.getValue().getData().newInput(); try { T value = coder.decode(inputStream, Coder.Context.OUTER); future.set(value); } catch (IOException e) { throw new IllegalStateException("Unable to decode value using " + coder, e); } } else { future.set(null); } } /** * An iterable over elements backed by paginated GetData requests to Windmill. The iterable may be * iterated over an arbitrary number of times and multiple iterators may be active simultaneously. * * There are two pattern we wish to support with low -memory and -latency: * * * Re-iterate over the initial elements multiple times (eg Iterables.first). We'll cache the * initial 'page' of values returned by Windmill from our first request for the lifetime of * the iterable. * Iterate through all elements of a very large collection. We'll send the GetData request * for the next page when the current page is begun. We'll discard intermediate pages and * only retain the first. Thus the maximum memory pressure is one page plus one page per * call to iterator. * */ private static class BagPagingIterable implements Iterable { /** * The reader we will use for scheduling continuation pages. * * NOTE We've made this explicit to remind us to be careful not to cache the iterable. */ private final WindmillStateReader reader; /** Initial values returned for the first page. Never reclaimed. */ private final List firstPage; /** State tag with continuation position set for second page. */ private final StateTag secondPagePos; /** Coder for elements. */ private final Coder elemCoder; private BagPagingIterable( WindmillStateReader reader, List firstPage, StateTag secondPagePos, Coder elemCoder) { this.reader = reader; this.firstPage = firstPage; this.secondPagePos = secondPagePos; this.elemCoder = elemCoder; } @Override public Iterator iterator() { return new AbstractIterator() { private Iterator currentPage = firstPage.iterator(); private StateTag nextPagePos = secondPagePos; private Future> pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); @Override protected T computeNext() { while (true) { if (currentPage.hasNext()) { return currentPage.next(); } if (pendingNextPage == null) { return endOfData(); } ValuesAndContPosition valuesAndContPosition; try { valuesAndContPosition = pendingNextPage.get(); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new RuntimeException("Unable to read value from state", e); } currentPage = valuesAndContPosition.values.iterator(); nextPagePos = new StateTag( nextPagePos.kind, nextPagePos.tag, nextPagePos.stateFamily, valuesAndContPosition.continuationPosition); pendingNextPage = // NOTE: The results of continuation page reads are never cached. reader.continuationBagFuture(nextPagePos, elemCoder); } } }; } } } |
blob | 1. long method, 2. blob | t | t | t | 1. long method | 0 | 9598 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/WindmillStateReader.java/#L61-L722 | 1 | 1070 | 9598 | minor | |
| 2220 | { "message": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | 1. data class | t | t | t | 0 | 13551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 2220 | 13551 | major | ||
| 181 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Data class" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | long method, data class | t | t | t | long method | 0 | 2064 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 181 | 2064 | critical | |
| 383 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | 1. long method | t | t | f | long method | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 383 | 3920 | minor | |
| 1461 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 1461 | 11023 | minor | |
| 1272 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1272 | 10573 | minor | ||
| 2432 | {"response": "YES I found bad smells the bad smells are: 1. Blob, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 14460 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 2432 | 14460 | major | |
| 3964 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting 5. Lack of comments/documentation 6. Poor variable naming 7. Potential for NullPointerException 8. Inefficient use of if/else blocks 9. Code repetition 10. Inappropriate use of nested loops 11. Poor exception handling 12. Potential for logical errors 13. Inconsistent use of braces 14. Lack of abstraction 15. Poor separation of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting5 Lack of comments/documentation6 Poor variable naming7 Potential for NullPointerException8 Inefficient use of if/else blocks9 Code repetition | t | f | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 3964 | 10391 | major | ||
| 466 | the bad smells are: 1. Long method 2. Feature envy 3. Conditional complexity (multiple nested if statements) 4. Inconsistent formatting and indentation 5. Unclear variable names 6. Lack of comments/documentation 7. Duplicate code (throwing the same exception for different conditions) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method2 Feature envy3 Conditional complexity (multiple nested if statements)4 Inconsistent formatting and indentation 5 Unclear variable names 6 Lack of comments/documentation 7 Duplicate code (throwing the same exception for different conditions) | f | f | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 466 | 4523 | major | ||
| 1623 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 2 | 1623 | 11490 | minor | ||
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 261 | 2843 | major | |
| 982 | YES I found bad smells the bad smells are: 1. Long method 2. Commented out code (case DEFAULT) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method2 Commented out code (case DEFAULT) | t | f | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 982 | 8859 | major | ||
| 1042 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1042 | 9438 | major | ||
| 2112 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 2112 | 13189 | major | |
| 1218 | YES I found bad smells the bad smells are: 1. Long method, 2. Complex conditionals, 3. Duplicate code, 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | Long method, 2 Complex conditionals, 3 Duplicate code, 4 Feature envy | t | f | t | . Long method, 2. Complex conditionals, 3. Duplicate code | 0 | 10324 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1218 | 10324 | major | |
| 351 | YES I found bad smells The bad smells are:1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3600 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 351 | 3600 | major | ||
| 5639 | { "message": "YES I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | long method | t | t | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5639 | 10918 | minor | ||
| 322 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public MessageReference copy(final Queue queue) { return new MessageReferenceImpl(this, queue); } |
feature envy | Feature envy | t | f | t | 0 | 3309 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/MessageReferenceImpl.java/#L137-L140 | 2 | 322 | 3309 | major | ||
| 757 | {"message":"YES I found bad smells","bad smells are":["1. Long Method","2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 757 | 7057 | major | |
| 705 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
blob | blob, long method | t | t | t | long method | 0 | 6714 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 1 | 705 | 6714 | major | |
| 378 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Use of switch statement instead of alternative strategies | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
feature envy | Long method2 Feature envy3 Duplicate code4 Use of switch statement instead of alternative strategies | t | f | t | 0 | 3904 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 378 | 3904 | major | ||
| 1818 | "YES I found bad smells" the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Magic numbers/strings 5. Catching general exceptions 6. Duplicated code 7. Poor error handling 8. Complex conditional logic 9. Unused or unnecessary variables 10. Hard-to-read variable names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long method2 Feature envy3 Nested loops4 Magic numbers/strings5 Catching general exceptions6 Duplicated code7 Poor error handling8 Complex conditional logic9 Unused or unnecessary variables | t | f | t | 0 | 12089 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1818 | 12089 | minor | ||
| 1626 | {"output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | Long Method, 2 Data Class"} | t | f | t | . Long Method | 0 | 11500 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 1 | 1626 | 11500 | minor | |
| 628 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 6271 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 628 | 6271 | major | ||
| 644 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6355 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 644 | 6355 | major | ||
| 2079 | {"response": "YES I found bad smells", "bad_smells": ["1. Long method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | 1. long method, 2. data class | t | t | f | 1. long method | data class | 0 | 13060 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2079 | 13060 | major |
| 1613 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3. Magic numbers/strings (e.g. -1, "Connection error while authenticating user") 4. Hard coded values (e.g. Version.CURRENT) 5. Code duplication (setting the secure part of the message twice) 6. Inconsistent formatting and indentation 7. Lack of proper error handling and comments/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | Long method2 Feature envy (the code is manipulating data belonging to the connection object instead of its own data) 3 Magic numbers/strings (eg - | t | f | t | 0 | 11470 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 1613 | 11470 | minor | ||
| 1031 | { "error": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1031 | 9386 | major | ||
| 2362 | YES I found bad smells The bad smells are: 1. Raw type usage 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
feature envy | Raw type usage2 Long method3 Feature envy | t | f | t | 0 | 14252 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 2362 | 14252 | minor | ||
| 2402 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 14382 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 2402 | 14382 | major | ||
| 829 | {"message":"YES I found bad smells","bad_smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | 1. long method | t | t | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 829 | 7728 | major | ||
| 3999 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | data class | t | t | t | 0 | 10569 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 3999 | 10569 | critical | ||
| 2397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14375 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2397 | 14375 | minor | ||
| 590 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Non-descriptive variable names 6. Deprecated code 7. Code commented out and not removed 8. Code that needs to be fixed (marked by FIXME) 9. Mixing of concerns (semantic check and inheritance check) 10. Mixing of levels of abstraction (parsing per clause and adding attribute to ajAttributes) 11. Unused variables (aspectAttribute) 12. Lack of error handling (returning false without specific error message) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Non-descriptive variable names6 Deprecated code7 Code commented out and not removed8 Code that needs to be fixed (marked by FIXME)9 Mixing of concerns (semantic check and inheritance check) | t | f | t | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 2 | 590 | 5890 | major | ||
| 2165 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2165 | 13347 | major | ||
| 361 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | long method | t | t | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 361 | 3699 | major | ||
| 429 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 4276 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 429 | 4276 | critical | ||
| 549 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | data class | t | t | t | 0 | 5558 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 549 | 5558 | major | ||
| 964 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Logging throughout the method 5. Throwable catch-all 6. Insufficient comments/documentation 7. Multiple nested levels of code 8. Debug flag usage 9. Non-descriptive variable names 10. Commented-out code 11. Unused/unnecessary imports 12. Dependency injection used only for testing purposes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method 2 Feature envy 3 Code duplication 4 Logging throughout the method 5 Throwable catch-all 6 Insufficient comments/documentation 7 Multiple nested levels of code 8 Debug flag usage 9 Non-descriptive variable names | t | f | t | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 964 | 8595 | major | ||
| 1332 | {"response": "YES I found bad smells. the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | 1. data class | t | t | t | 0 | 10716 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 1332 | 10716 | critical | ||
| 1287 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1287 | 10613 | minor | ||
| 780 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method, blob | t | t | t | blob | 0 | 7455 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 780 | 7455 | minor | |
| 1898 | YES found bad smells Amongst the bad smells found are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 1898 | 12351 | major | ||
| 1006 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | 1. long method | t | t | t | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 1006 | 9258 | major | ||
| 205 | {"message": "YES I found bad smells", "badsmells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | blob, data class | t | t | t | blob | 0 | 2299 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 1 | 205 | 2299 | minor | |
| 367 | {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | blob, data class | t | t | t | blob | 0 | 3757 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 1 | 367 | 3757 | major | |
| 1342 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10744 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 2 | 1342 | 10744 | minor | ||
| 1025 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplicate code in switch statement 5. Nested if/else statements 6. Poor variable naming 7. Potential for NullPointerException | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | Long method2 Feature envy3 Magic numbers4 Duplicate code in switch statement5 Nested if/else statements 6 Poor variable naming 7 Potential for NullPointerException | t | f | t | 0 | 9360 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1025 | 9360 | major | ||
| 1140 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
long method | blob, long method | t | t | t | blob | 0 | 10089 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 1 | 1140 | 10089 | minor | |
| 1796 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1796 | 11999 | minor | ||
| 5500 | YES, I found bad smells in the following code. The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final Iterator applyAll(final S start, final Traversal.Admin traversal) { traversal.reset(); traversal.addStart(traversal.getTraverserGenerator().generate(start, traversal.getStartStep(), 1l)); return traversal; // flatMap } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3063 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalUtil.java/#L99-L103 | 1 | 5500 | 3063 | major | ||
| 1635 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1635 | 11522 | minor | ||
| 5638 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5638 | 10869 | major | ||
| 1933 | YES I found bad smells the bad smells are: 1.Long method, 2. Feature envy, 3. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | Long method, 2 Feature envy, 3 Code duplication | t | f | t | 2. Feature envy, 3. Code duplication. | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 1933 | 12457 | minor | |
| 878 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | data class | t | t | t | 0 | 8012 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 878 | 8012 | critical | ||
| 1523 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long Method | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 1523 | 11179 | minor | ||
| 1647 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1647 | 11563 | critical | ||
| 450 | YES, I found bad smells. The bad smells are: 1. Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings. 2. Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand. 3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain. 4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods. 5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about. 6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues. 7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug. 8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read. 9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Magic literal - the "unchecked" in the @SuppressWarnings annotation, makes it hard to understand the purpose of suppressing warnings2 Long method - the method handleBulkLoad is long and contains multiple nested loops and conditions, which makes it hard to read and understand3 Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain4 Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods5 Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about6 Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues7 Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug8 Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read9 Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain | t | f | t | . Magic literal - the "unchecked" in the @SuppressWarnings annotation, which makes it hard to read and understand.3. Feature envy - the method contains code that is more interested in other classes or objects, leading to dependencies that can be difficult to maintain.4. Lack of proper abstraction - the method is performing multiple operations, such as getting the file system and creating directories, which should be abstracted into separate methods.5. Complex conditionals - the if statements in the code contain complex conditions, which can be hard to understand and reason about.6. Duplicate code - the log statements for tracing are duplicated, which can lead to maintenance issues.7. Deep nesting - the code contains multiple levels of nested loops and conditionals, which can make it difficult to understand and debug.8. Use of primitives - the code is using strings and arrays of strings instead of using proper data structures, which can lead to errors and make the code difficult to read.9. Inconsistent formatting - the code uses different styles of indentation and spacing, which can make it hard to read and maintain. | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 450 | 4392 | minor | |
| 342 | YES I found bad smells: 1. Long method 2. Feature envy 3. Data class violation 4. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy3 Data class violation4 Primitive obsession | t | f | t | 0 | 3502 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 342 | 3502 | major | ||
| 105 | { "response": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 1384 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 1 | 105 | 1384 | major | ||
| 2481 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14598 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 2481 | 14598 | minor | |
| 2188 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13444 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 2188 | 13444 | minor | |
| 3002 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | 1. data class | t | t | t | 0 | 3071 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 1 | 3002 | 3071 | major | ||
| 1950 | { "message": "YES, I found bad smells", "bad smells are": ["Blob", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | blob, data class | t | t | f | blob | data class | 0 | 12530 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 1 | 1950 | 12530 | minor |
| 1101 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9839 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1101 | 9839 | major | ||
| 3521 | { "input_code": "public class Example {\n private int a;\n private int b;\n \n public int calculateSum() {\n return a + b;\n }\n\n public void printValues() {\n System.out.println(\"Value a: \" + a);\n System.out.println(\"Value b: \" + b);\n }\n}", "detected_code_smells": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smellsthe bad smells are:1. long method | t | t | t | 0 | 7615 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src-gen/org/eclipse/n4js/ui/contentassist/antlr/internal/InternalN4JSParser.java/#L181223-L181248 | 1 | 3521 | 7615 | minor | ||
| 2540 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2540 | 14774 | major | |
| 1117 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Nested loops 6. Long parameter list 7. Tight coupling 8. Non-descriptive variable naming 9. Redundant code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Duplicate code4 Complex conditional statements5 Nested loops6 Long parameter list7 Tight coupling8 Non-descriptive variable naming9 Redundant code | t | f | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1117 | 9955 | critical | ||
| 1111 | Yes I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private IgniteFuture startRemoteListenAsync(BinaryRawReaderEx reader, IgniteMessaging messaging) { Object nativeFilter = reader.readObjectDetached(); long ptr = reader.readLong(); // interop pointer Object topic = reader.readObjectDetached(); PlatformMessageFilter filter = platformCtx.createRemoteMessageFilter(nativeFilter, ptr); return messaging.remoteListenAsync(topic, filter); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9888 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/messaging/PlatformMessaging.java/#L185-L195 | 2 | 1111 | 9888 | minor | ||
| 462 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 462 | 4467 | minor | ||
| 1050 | YES I found bad smells the bad smells are: 1.Long method 2.Long method 3.Unnecessary comments 4.Lack of proper indentation/formatting 5.Lack of proper variable naming 6.Feature envy 7.Magic numbers/strings used in code 8.Manually handling exceptions instead of using try-catch blocks 9.Accessing properties multiple times instead of storing them in a variable 10.Multiple nested if-else statements 11.Missing error handling for exceptions 12.Hard-coded class and method names instead of using reflection 13.Large number of method calls 14.Methods performing multiple actions instead of a single, specific task. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2Long method3Unnecessary comments4Lack of proper indentation/formatting5Lack of proper variable naming6Feature envy7Magic numbers/strings used in code8Manually handling exceptions instead of using try-catch blocks9Accessing properties multiple times instead of storing them in a variable | t | f | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1050 | 9476 | major | ||
| 815 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KerningRecord implements IDataType { private int code1; private int code2; private int adjustment; /** * @return the code1 */ public int getCode1() { return code1; } /** * @param code1 the code1 to set */ public void setCode1(int code1) { this.code1 = code1; } /** * @return the code2 */ public int getCode2() { return code2; } /** * @param code2 the code2 to set */ public void setCode2(int code2) { this.code2 = code2; } /** * @return the adjustment */ public int getAdjustment() { return adjustment; } /** * @param adjustment the adjustment to set */ public void setAdjustment(int adjustment) { this.adjustment = adjustment; } } |
data class | data class | t | t | t | 0 | 7659 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler/src/main/java/org/apache/royale/swf/types/KerningRecord.java/#L30-L83 | 1 | 815 | 7659 | critical | ||
| 1657 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 1657 | 11601 | minor | ||
| 1732 | {"answer": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | 1 Long Method | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 1 | 1732 | 11821 | critical | ||
| 558 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | long method, data class | t | t | f | long method | data class | 0 | 5621 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 1 | 558 | 5621 | major |
| 267 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class MultiPointList extends AbstractList { private final MultiPoint mp; public MultiPointList(MultiPoint mp) { this.mp = mp; } @Override public Point get(int index) { return mp.getPoint(index); } @Override public int size() { return mp.getPointCount(); } } |
data class | long method, data class | t | t | t | long method | 0 | 2884 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-commons/geoportal-commons-geometry/src/main/java/com/esri/geoportal/geoportal/commons/geometry/GeometryService.java/#L201-L217 | 1 | 267 | 2884 | minor | |
| 583 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 5796 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 583 | 5796 | critical | |
| 1594 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | Blob, Data Class | t | f | t | Blob | 0 | 11407 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 1594 | 11407 | critical | |
| 338 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | blob, data class, long method | t | t | f | blob, long method | data class | 0 | 3483 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 1 | 338 | 3483 | critical |
| 48 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Repeated code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method, repeated code | t | t | t | repeated code | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 48 | 854 | minor | |
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 240 | 2628 | major | ||
| 1003 | Yes, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inappropriate naming convention (variable names) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy3 Inappropriate naming convention (variable names) | t | f | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1003 | 9230 | minor | ||
| 4051 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10700 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 4051 | 10700 | major | ||
| 1526 | { "answer": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | Data Class | t | f | t | 0 | 11186 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 1526 | 11186 | minor | ||
| 974 | { "response": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | data class | t | t | t | 0 | 8777 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 1 | 974 | 8777 | minor | ||
| 2588 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 14994 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 2588 | 14994 | critical | ||
| 1125 | YES I found bad smells. The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method | t | f | t | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 1125 | 10003 | minor | ||
| 2026 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 12803 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 1 | 2026 | 12803 | minor | |
| 4065 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | long method | t | t | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 1 | 4065 | 10729 | minor | ||
| 259 | {"output": "YES I found bad smells\nthe bad smells are: 1. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | 1. data class | t | t | t | 0 | 2812 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 259 | 2812 | critical | ||
| 402 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 402 | 4103 | major | ||
| 1838 | YES I found bad smells the bad smells are: - Long method - Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | - Long method- Feature envy | t | f | t | 0 | 12143 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 1838 | 12143 | minor | ||
| 5584 | YES I found bad smells the smells are: 1. Feature envy 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Feature envy2 Long method | t | f | t | 0 | 9276 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5584 | 9276 | major | ||
| 972 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | data class | t | t | t | 0 | 8715 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 972 | 8715 | major | ||
| 2289 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | data class, long method | t | t | t | long method | 0 | 13914 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 2289 | 13914 | minor | |
| 2527 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2527 | 14726 | major | ||
| 3834 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9880 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 3834 | 9880 | minor | ||
| 2088 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code (in the if statement) 4. Magic numbers (100, 2, etc.) 5. Inconsistent formatting (braces placement) 6. Inconsistent naming conventions (getLastMessageIdAsync vs getLastMessageIdFuture) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | Feature envy2 Long method3 Duplicate code (in the if statement)4 Magic numbers ( | t | f | t | 0 | 13108 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 2 | 2088 | 13108 | minor | ||
| 787 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method | t | t | t | 0 | 7509 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 787 | 7509 | minor | ||
| 1505 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | data class | t | t | t | 0 | 11149 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 1505 | 11149 | major | ||
| 2627 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | data class | t | t | t | 0 | 15086 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 2627 | 15086 | major | ||
| 5193 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | 1. long method | t | t | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 5193 | 14519 | major | ||
| 441 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 4302 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 441 | 4302 | critical |
| 1769 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11918 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 1769 | 11918 | minor | |
| 2374 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 14314 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 2374 | 14314 | major | |
| 2252 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 13680 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 2252 | 13680 | major | ||
| 1502 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | long method, data class | t | t | t | data class | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 1502 | 11135 | critical | |
| 2395 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2395 | 14373 | major | |
| 5271 | * * YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method2 Feature envy | t | f | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5271 | 14741 | minor | ||
| 2058 | YES I found bad smells the bad smells are: 1. Long Parameter List 2. Long Method 3. Data Class 4. Feature Envy 5. Switch Statements 6. Lazy Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | Long Parameter List2 Long Method3 Data Class4 Feature Envy5 Switch Statements6 Lazy Class | t | f | t | 0 | 12960 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 2 | 2058 | 12960 | major | ||
| 36 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 1 | 36 | 754 | minor | ||
| 1680 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 1680 | 11666 | minor | ||
| 2072 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 2072 | 13027 | major | ||
| 3903 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3903 | 10219 | critical | ||
| 1038 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeated code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | Long method2 Repeated code3 Feature envy | t | f | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 2 | 1038 | 9410 | minor | ||
| 4605 | {"response":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | long method | t | t | t | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 1 | 4605 | 12253 | minor | ||
| 671 | { "output": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method, blob | t | t | t | blob | 0 | 6554 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 671 | 6554 | major | |
| 1058 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Use of temporary variables 5. Exception handling inside a loop 6. Use of constant strings instead of enums 7. Use of raw types in collections 8. Use of multiple try-catch blocks with similar code 9. Poor exception handling (only logging the exception) 10. Lack of comments or documentation for complex logic and data structures. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy3 Duplicated code4 Use of temporary variables5 Exception handling inside a loop6 Use of constant strings instead of enums7 Use of raw types in collections8 Use of multiple try-catch blocks with similar code9 Poor exception handling (only logging the exception) | t | f | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1058 | 9520 | major | ||
| 2533 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14745 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 2533 | 14745 | minor | ||
| 2105 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 2105 | 13169 | minor | ||
| 689 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | 1. long method | t | t | t | 0 | 6635 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 689 | 6635 | major | ||
| 540 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | data class | t | t | t | 0 | 5535 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 540 | 5535 | major | ||
| 1417 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | blob, data class | t | t | t | blob | 0 | 10917 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 1 | 1417 | 10917 | minor | |
| 918 | YES I found bad smells. the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 8254 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 2 | 918 | 8254 | major | |
| 2186 | YES I found bad smells The bad smells are: 1. Large Class, 2. Large Method, 3. Data Class, 4. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | Large Class, 2 Large Method, 3 Data Class, 4 Long Parameter List | t | f | t | . Large Class, 2. Large Method, 4. Long Parameter List | 0 | 13435 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 2 | 2186 | 13435 | major | |
| 2486 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14610 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 2486 | 14610 | minor | |
| 2367 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14300 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 1 | 2367 | 14300 | minor | |
| 2214 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | data class | t | t | t | 0 | 13528 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 1 | 2214 | 13528 | major | ||
| 2267 | { "output": "YES, I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | data class, long method | t | t | t | long method | 0 | 13734 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 2267 | 13734 | critical | |
| 3803 | "}; YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions 4. Use of raw types without generics 5. Unnecessary comments 6. Poor error handling 7. Unnecessary complexity 8. Magic numbers without meaningful names 9. Code redundancy 10. Dependency on hardcoded values 11. Inefficient use of data structures 12. Lack of proper error/exception handling 13. Mixing of different responsibilities in one method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
feature envy | Long method2 Feature envy 3 Inconsistent naming conventions 4 Use of raw types without generics 5 Unnecessary comments 6 Poor error handling 7 Unnecessary complexity 8 Magic numbers without meaningful names 9 Code redundancy | t | f | t | 0 | 9644 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 3803 | 9644 | minor | ||
| 468 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 468 | 4551 | major | ||
| 5757 | {"response": "YES I found bad smells","bad smells are": ["1. Long method","2. Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
feature envy | 1. long method, 2. feature envy | t | t | f | 1. long method | feature envy | 0 | 14502 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5757 | 14502 | minor |
| 1394 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1394 | 10850 | major | ||
| 430 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Data clumps, 4. Comments to explain code, 5. Code duplication, 6. Inappropriate coupling, | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | Long method, 2 Feature envy, 3 Data clumps, 4 Comments to explain code, 5 Code duplication, 6 Inappropriate coupling, | t | f | t | . Long method, 3. Data clumps, 4. Comments to explain code, 5. Code duplication, 6. Inappropriate coupling, | 0 | 4277 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 430 | 4277 | critical | |
| 216 | {"response": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 216 | 2343 | major | |
| 1204 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10287 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 1204 | 10287 | critical | |
| 1298 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | long method, blob | t | t | t | blob | 0 | 10639 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 1298 | 10639 | major | |
| 1008 | Yes I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method | t | f | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1008 | 9268 | major | ||
| 4521 | { "result": "YES I found bad smells", "the bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TopicSubscription extends AbstractSubscription { private static final Logger LOG = LoggerFactory.getLogger(TopicSubscription.class); private static final AtomicLong CURSOR_NAME_COUNTER = new AtomicLong(0); protected PendingMessageCursor matched; protected final SystemUsage usageManager; boolean singleDestination = true; Destination destination; private final Scheduler scheduler; private int maximumPendingMessages = -1; private MessageEvictionStrategy messageEvictionStrategy = new OldestMessageEvictionStrategy(); private int discarded; private final Object matchedListMutex = new Object(); private int memoryUsageHighWaterMark = 95; // allow duplicate suppression in a ring network of brokers protected int maxProducersToAudit = 1024; protected int maxAuditDepth = 1000; protected boolean enableAudit = false; protected ActiveMQMessageAudit audit; protected boolean active = false; protected boolean discarding = false; private boolean useTopicSubscriptionInflightStats = true; //Used for inflight message size calculations protected final Object dispatchLock = new Object(); protected final List dispatched = new ArrayList<>(); public TopicSubscription(Broker broker,ConnectionContext context, ConsumerInfo info, SystemUsage usageManager) throws Exception { super(broker, context, info); this.usageManager = usageManager; String matchedName = "TopicSubscription:" + CURSOR_NAME_COUNTER.getAndIncrement() + "[" + info.getConsumerId().toString() + "]"; if (info.getDestination().isTemporary() || broker.getTempDataStore()==null ) { this.matched = new VMPendingMessageCursor(false); } else { this.matched = new FilePendingMessageCursor(broker,matchedName,false); } this.scheduler = broker.getScheduler(); } public void init() throws Exception { this.matched.setSystemUsage(usageManager); this.matched.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark()); this.matched.start(); if (enableAudit) { audit= new ActiveMQMessageAudit(maxAuditDepth, maxProducersToAudit); } this.active=true; } @Override public void add(MessageReference node) throws Exception { if (isDuplicate(node)) { return; } // Lets use an indirect reference so that we can associate a unique // locator /w the message. node = new IndirectMessageReference(node.getMessage()); getSubscriptionStatistics().getEnqueues().increment(); synchronized (matchedListMutex) { // if this subscriber is already discarding a message, we don't want to add // any more messages to it as those messages can only be advisories generated in the process, // which can trigger the recursive call loop if (discarding) return; if (!isFull() && matched.isEmpty()) { // if maximumPendingMessages is set we will only discard messages which // have not been dispatched (i.e. we allow the prefetch buffer to be filled) dispatch(node); setSlowConsumer(false); } else { if (info.getPrefetchSize() > 1 && matched.size() > info.getPrefetchSize()) { // Slow consumers should log and set their state as such. if (!isSlowConsumer()) { LOG.warn("{}: has twice its prefetch limit pending, without an ack; it appears to be slow", toString()); setSlowConsumer(true); for (Destination dest: destinations) { dest.slowConsumer(getContext(), this); } } } if (maximumPendingMessages != 0) { boolean warnedAboutWait = false; while (active) { while (matched.isFull()) { if (getContext().getStopping().get()) { LOG.warn("{}: stopped waiting for space in pendingMessage cursor for: {}", toString(), node.getMessageId()); getSubscriptionStatistics().getEnqueues().decrement(); return; } if (!warnedAboutWait) { LOG.info("{}: Pending message cursor [{}] is full, temp usag ({}%) or memory usage ({}%) limit reached, blocking message add() pending the release of resources.", new Object[]{ toString(), matched, matched.getSystemUsage().getTempUsage().getPercentUsage(), matched.getSystemUsage().getMemoryUsage().getPercentUsage() }); warnedAboutWait = true; } matchedListMutex.wait(20); } // Temporary storage could be full - so just try to add the message // see https://issues.apache.org/activemq/browse/AMQ-2475 if (matched.tryAddMessageLast(node, 10)) { break; } } if (maximumPendingMessages > 0) { // calculate the high water mark from which point we // will eagerly evict expired messages int max = messageEvictionStrategy.getEvictExpiredMessagesHighWatermark(); if (maximumPendingMessages > 0 && maximumPendingMessages < max) { max = maximumPendingMessages; } if (!matched.isEmpty() && matched.size() > max) { removeExpiredMessages(); } // lets discard old messages as we are a slow consumer while (!matched.isEmpty() && matched.size() > maximumPendingMessages) { int pageInSize = matched.size() - maximumPendingMessages; // only page in a 1000 at a time - else we could blow the memory pageInSize = Math.max(1000, pageInSize); LinkedList list = null; MessageReference[] oldMessages=null; synchronized(matched){ list = matched.pageInList(pageInSize); oldMessages = messageEvictionStrategy.evictMessages(list); for (MessageReference ref : list) { ref.decrementReferenceCount(); } } int messagesToEvict = 0; if (oldMessages != null){ messagesToEvict = oldMessages.length; for (int i = 0; i < messagesToEvict; i++) { MessageReference oldMessage = oldMessages[i]; discard(oldMessage); } } // lets avoid an infinite loop if we are given a bad eviction strategy // for a bad strategy lets just not evict if (messagesToEvict == 0) { LOG.warn("No messages to evict returned for {} from eviction strategy: {} out of {} candidates", new Object[]{ destination, messageEvictionStrategy, list.size() }); break; } } } dispatchMatched(); } } } } private boolean isDuplicate(MessageReference node) { boolean duplicate = false; if (enableAudit && audit != null) { duplicate = audit.isDuplicate(node); if (LOG.isDebugEnabled()) { if (duplicate) { LOG.debug("{}, ignoring duplicate add: {}", this, node.getMessageId()); } } } return duplicate; } /** * Discard any expired messages from the matched list. Called from a * synchronized block. * * @throws IOException */ protected void removeExpiredMessages() throws IOException { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.isExpired()) { matched.remove(); node.decrementReferenceCount(); if (broker.isExpired(node)) { ((Destination) node.getRegionDestination()).getDestinationStatistics().getExpired().increment(); broker.messageExpired(getContext(), node, this); } break; } } } finally { matched.release(); } } @Override public void processMessageDispatchNotification(MessageDispatchNotification mdn) { synchronized (matchedListMutex) { try { matched.reset(); while (matched.hasNext()) { MessageReference node = matched.next(); node.decrementReferenceCount(); if (node.getMessageId().equals(mdn.getMessageId())) { synchronized(dispatchLock) { matched.remove(); getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } node.decrementReferenceCount(); } break; } } } finally { matched.release(); } } } @Override public synchronized void acknowledge(final ConnectionContext context, final MessageAck ack) throws Exception { super.acknowledge(context, ack); if (ack.isStandardAck()) { updateStatsOnAck(context, ack); } else if (ack.isPoisonAck()) { if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } updateStatsOnAck(context, ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isIndividualAck()) { updateStatsOnAck(context, ack); if (ack.isInTransaction()) { expandPrefetchExtension(1); } } else if (ack.isExpiredAck()) { updateStatsOnAck(ack); contractPrefetchExtension(ack.getMessageCount()); } else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch counters. expandPrefetchExtension(ack.getMessageCount()); } else if (ack.isRedeliveredAck()) { // No processing for redelivered needed return; } else { throw new JMSException("Invalid acknowledgment: " + ack); } dispatchMatched(); } private void updateStatsOnAck(final ConnectionContext context, final MessageAck ack) { if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterRollback() { contractPrefetchExtension(ack.getMessageCount()); } @Override public void afterCommit() throws Exception { contractPrefetchExtension(ack.getMessageCount()); updateStatsOnAck(ack); dispatchMatched(); } }); } else { updateStatsOnAck(ack); } } @Override public Response pullMessage(ConnectionContext context, final MessagePull pull) throws Exception { // The slave should not deliver pull messages. if (getPrefetchSize() == 0) { final long currentDispatchedCount = getSubscriptionStatistics().getDispatched().getCount(); prefetchExtension.set(pull.getQuantity()); dispatchMatched(); // If there was nothing dispatched.. we may need to setup a timeout. if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || pull.isAlwaysSignalDone()) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message to signal nothing pending. dispatch(null); prefetchExtension.set(0); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { @Override public void run() { pullTimeout(currentDispatchedCount, pull.isAlwaysSignalDone()); } }, pull.getTimeout()); } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ private final void pullTimeout(long currentDispatchedCount, boolean alwaysSendDone) { synchronized (matchedListMutex) { if (currentDispatchedCount == getSubscriptionStatistics().getDispatched().getCount() || alwaysSendDone) { try { dispatch(null); } catch (Exception e) { context.getConnection().serviceException(e); } finally { prefetchExtension.set(0); } } } } /** * Update the statistics on message ack. * @param ack */ private void updateStatsOnAck(final MessageAck ack) { //Allow disabling inflight stats to save memory usage if (isUseTopicSubscriptionInflightStats()) { synchronized(dispatchLock) { boolean inAckRange = false; List removeList = new ArrayList<>(); for (final DispatchedNode node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { removeList.add(node); if (ack.getLastMessageId().equals(messageId)) { break; } } } for (final DispatchedNode node : removeList) { dispatched.remove(node); getSubscriptionStatistics().getInflightMessageSize().addSize(-node.getSize()); final Destination destination = node.getDestination(); incrementStatsOnAck(destination, ack, 1); if (!ack.isInTransaction()) { contractPrefetchExtension(1); } } } } else { if (singleDestination && destination != null) { incrementStatsOnAck(destination, ack, ack.getMessageCount()); } if (!ack.isInTransaction()) { contractPrefetchExtension(ack.getMessageCount()); } } } private void incrementStatsOnAck(final Destination destination, final MessageAck ack, final int count) { getSubscriptionStatistics().getDequeues().add(count); destination.getDestinationStatistics().getDequeues().add(count); destination.getDestinationStatistics().getInflight().subtract(count); if (info.isNetworkSubscription()) { destination.getDestinationStatistics().getForwards().add(count); } if (ack.isExpiredAck()) { destination.getDestinationStatistics().getExpired().add(count); } } @Override public int countBeforeFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() : info.getPrefetchSize() + prefetchExtension.get() - getDispatchedQueueSize(); } @Override public int getPendingQueueSize() { return matched(); } @Override public long getPendingMessageSize() { synchronized (matchedListMutex) { return matched.messageSize(); } } @Override public int getDispatchedQueueSize() { return (int)(getSubscriptionStatistics().getDispatched().getCount() - getSubscriptionStatistics().getDequeues().getCount()); } public int getMaximumPendingMessages() { return maximumPendingMessages; } @Override public long getDispatchedCounter() { return getSubscriptionStatistics().getDispatched().getCount(); } @Override public long getEnqueueCounter() { return getSubscriptionStatistics().getEnqueues().getCount(); } @Override public long getDequeueCounter() { return getSubscriptionStatistics().getDequeues().getCount(); } /** * @return the number of messages discarded due to being a slow consumer */ public int discarded() { synchronized (matchedListMutex) { return discarded; } } /** * @return the number of matched messages (messages targeted for the * subscription but not yet able to be dispatched due to the * prefetch buffer being full). */ public int matched() { synchronized (matchedListMutex) { return matched.size(); } } /** * Sets the maximum number of pending messages that can be matched against * this consumer before old messages are discarded. */ public void setMaximumPendingMessages(int maximumPendingMessages) { this.maximumPendingMessages = maximumPendingMessages; } public MessageEvictionStrategy getMessageEvictionStrategy() { return messageEvictionStrategy; } /** * Sets the eviction strategy used to decide which message to evict when the * slow consumer needs to discard messages */ public void setMessageEvictionStrategy(MessageEvictionStrategy messageEvictionStrategy) { this.messageEvictionStrategy = messageEvictionStrategy; } public int getMaxProducersToAudit() { return maxProducersToAudit; } public synchronized void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; if (audit != null) { audit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } } public int getMaxAuditDepth() { return maxAuditDepth; } public synchronized void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; if (audit != null) { audit.setAuditDepth(maxAuditDepth); } } public boolean isEnableAudit() { return enableAudit; } public synchronized void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; if (enableAudit && audit == null) { audit = new ActiveMQMessageAudit(maxAuditDepth,maxProducersToAudit); } } // Implementation methods // ------------------------------------------------------------------------- @Override public boolean isFull() { return getPrefetchSize() == 0 ? prefetchExtension.get() == 0 : getDispatchedQueueSize() - prefetchExtension.get() >= info.getPrefetchSize(); } @Override public int getInFlightSize() { return getDispatchedQueueSize(); } /** * @return true when 60% or more room is left for dispatching messages */ @Override public boolean isLowWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ @Override public boolean isHighWaterMark() { return (getDispatchedQueueSize() - prefetchExtension.get()) >= (info.getPrefetchSize() * .9); } /** * @param memoryUsageHighWaterMark the memoryUsageHighWaterMark to set */ public void setMemoryUsageHighWaterMark(int memoryUsageHighWaterMark) { this.memoryUsageHighWaterMark = memoryUsageHighWaterMark; } /** * @return the memoryUsageHighWaterMark */ public int getMemoryUsageHighWaterMark() { return this.memoryUsageHighWaterMark; } /** * @return the usageManager */ public SystemUsage getUsageManager() { return this.usageManager; } /** * @return the matched */ public PendingMessageCursor getMatched() { return this.matched; } /** * @param matched the matched to set */ public void setMatched(PendingMessageCursor matched) { this.matched = matched; } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ @Override public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } private void dispatchMatched() throws IOException { synchronized (matchedListMutex) { if (!matched.isEmpty() && !isFull()) { try { matched.reset(); while (matched.hasNext() && !isFull()) { MessageReference message = matched.next(); message.decrementReferenceCount(); matched.remove(); // Message may have been sitting in the matched list a while // waiting for the consumer to ak the message. if (message.isExpired()) { discard(message); continue; // just drop it. } dispatch(message); } } finally { matched.release(); } } } } private void dispatch(final MessageReference node) throws IOException { Message message = node != null ? node.getMessage() : null; if (node != null) { node.incrementReferenceCount(); } // Make sure we can dispatch a message. MessageDispatch md = new MessageDispatch(); md.setMessage(message); md.setConsumerId(info.getConsumerId()); if (node != null) { md.setDestination(((Destination)node.getRegionDestination()).getActiveMQDestination()); synchronized(dispatchLock) { getSubscriptionStatistics().getDispatched().increment(); if (isUseTopicSubscriptionInflightStats()) { dispatched.add(new DispatchedNode(node)); getSubscriptionStatistics().getInflightMessageSize().addSize(node.getSize()); } } // Keep track if this subscription is receiving messages from a single destination. if (singleDestination) { if (destination == null) { destination = (Destination)node.getRegionDestination(); } else { if (destination != node.getRegionDestination()) { singleDestination = false; } } } if (getPrefetchSize() == 0) { decrementPrefetchExtension(1); } } if (info.isDispatchAsync()) { if (node != null) { md.setTransmitCallback(new TransmitCallback() { @Override public void onSuccess() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } @Override public void onFailure() { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } }); } context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); if (node != null) { Destination regionDestination = (Destination) node.getRegionDestination(); regionDestination.getDestinationStatistics().getDispatched().increment(); regionDestination.getDestinationStatistics().getInflight().increment(); node.decrementReferenceCount(); } } } private void discard(MessageReference message) { discarding = true; try { message.decrementReferenceCount(); matched.remove(message); discarded++; if (destination != null) { destination.getDestinationStatistics().getDequeues().increment(); } LOG.debug("{}, discarding message {}", this, message); Destination dest = (Destination) message.getRegionDestination(); if (dest != null) { dest.messageDiscarded(getContext(), this, message); } broker.getRoot().sendToDeadLetterQueue(getContext(), message, this, new Throwable("TopicSubDiscard. ID:" + info.getConsumerId())); } finally { discarding = false; } } @Override public String toString() { return "TopicSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + destinations.size() + ", dispatched=" + getDispatchedQueueSize() + ", delivered=" + getDequeueCounter() + ", matched=" + matched() + ", discarded=" + discarded() + ", prefetchExtension=" + prefetchExtension.get() + ", usePrefetchExtension=" + isUsePrefetchExtension(); } @Override public void destroy() { this.active=false; synchronized (matchedListMutex) { try { matched.destroy(); } catch (Exception e) { LOG.warn("Failed to destroy cursor", e); } } setSlowConsumer(false); synchronized(dispatchLock) { dispatched.clear(); } } @Override public int getPrefetchSize() { return info.getPrefetchSize(); } @Override public void setPrefetchSize(int newSize) { info.setPrefetchSize(newSize); try { dispatchMatched(); } catch(Exception e) { LOG.trace("Caught exception on dispatch after prefetch size change."); } } public boolean isUseTopicSubscriptionInflightStats() { return useTopicSubscriptionInflightStats; } public void setUseTopicSubscriptionInflightStats(boolean useTopicSubscriptionInflightStats) { this.useTopicSubscriptionInflightStats = useTopicSubscriptionInflightStats; } private static class DispatchedNode { private final int size; private final MessageId messageId; private final Destination destination; public DispatchedNode(final MessageReference node) { super(); this.size = node.getSize(); this.messageId = node.getMessageId(); this.destination = node.getRegionDestination() instanceof Destination ? ((Destination)node.getRegionDestination()) : null; } public long getSize() { return size; } public MessageId getMessageId() { return messageId; } public Destination getDestination() { return destination; } } } |
blob | long method, blob | t | t | t | long method | 0 | 11993 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/TopicSubscription.java/#L51-L817 | 1 | 4521 | 11993 | critical | |
| 660 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 6430 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 660 | 6430 | major | ||
| 5028 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | data class | t | t | t | 0 | 13962 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 5028 | 13962 | major | ||
| 2272 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2272 | 13768 | major | ||
| 385 | YES, I found bad smells the bad smells are: 1. Long method 2. Long class 3. Shotgun surgery 4. Feature envy 5. Data class 6. God class 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Long method2 Long class3 Shotgun surgery4 Feature envy 5 Data class 6 God class7 Lazy class | t | f | t | 0 | 3938 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 2 | 385 | 3938 | minor | ||
| 2545 | YES, I found bad smells The bad smells are: 1. Long method 2. Unnecessary use of boolean flags 3. Mixing of concerns (i.e. handling memory management and file writing in the same method) 4. Magic numbers (i.e. the use of the number 3 in the memory size check) 5. Inconsistent naming conventions (i.e. using both camel case and snake case) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long method2 Unnecessary use of boolean flags3 Mixing of concerns (ie handling memory management and file writing in the same method)4 Magic numbers (ie the use of the number 3 in the memory size check)5 Inconsistent naming conventions (ie using both camel case and snake case) | t | f | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 2545 | 14790 | major | ||
| 1773 | YES I found bad smells the bad smells are: 1. Long method, 2. Data class, 3. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | Long method, 2 Data class, 3 Inappropriate intimacy | t | f | t | . Long method, 3. Inappropriate intimacy | 0 | 11931 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 2 | 1773 | 11931 | major | |
| 408 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | 1. data class | t | t | t | 0 | 4156 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 408 | 4156 | major | ||
| 2149 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method | t | t | t | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 2149 | 13283 | major | ||
| 1047 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 9457 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1047 | 9457 | minor | |
| 2552 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14803 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 2552 | 14803 | minor | |
| 1898 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | \n1. long method | t | t | t | 0 | 12351 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 1898 | 12351 | major | ||
| 2303 | { "response": "YES, I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | data class | t | t | t | 0 | 14060 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 1 | 2303 | 14060 | major | ||
| 3381 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | 1. long method | t | t | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 3381 | 6543 | major | ||
| 717 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | long method, data class | t | t | t | data class | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 1 | 717 | 6826 | minor | |
| 401 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 4102 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 401 | 4102 | minor | |
| 2154 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 13296 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 2154 | 13296 | minor |
| 2193 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2193 | 13477 | major | |
| 1547 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long Method | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 1547 | 11256 | critical | ||
| 2822 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | 1. long method | t | t | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 1 | 2822 | 1499 | major | ||
| 2307 | YES I found bad smells the bad smells are: 1. long method 2. feature envy 3. inconsistent naming conventions 4. unnecessary comments 5. lack of proper documentation or comments 6. hard-coded values 7. unnecessary type casting 8. long variable names 9. nested loops 10. excessive use of if/else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method2 feature envy3 inconsistent naming conventions4 unnecessary comments5 lack of proper documentation or comments6 hard-coded values7 unnecessary type casting8 long variable names9 nested loops | t | f | t | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 2307 | 14085 | major | ||
| 2137 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | data class | t | t | t | 0 | 13258 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 1 | 2137 | 13258 | major | ||
| 379 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | 1. long method | t | t | f | long method | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 1 | 379 | 3905 | minor | |
| 1695 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Nested Synchronization, 4. Multiple exception types, 5. Hard coding, 6. Magic numbers, 7. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
feature envy | Long method, 2 Feature envy, 3 Nested Synchronization, 4 Multiple exception types, 5 Hard coding, 6 Magic numbers, 7 Code duplication | t | f | t | . Long method, 3. Nested Synchronization, 4. Multiple exception types, 5. Hard coding, 6. Magic numbers, 7. Code duplication. | 0 | 11719 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1695 | 11719 | minor | |
| 1970 | { "output": "YES I found bad smells", "message": "the bad smells are:", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1970 | 12607 | minor | |
| 308 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RewriteLoadBalancerClient implements LoadBalancerClient { private static final Logger _log = LoggerFactory.getLogger(TrackerClient.class); private final String _serviceName; private final URI _uri; private final RewriteClient _client; public RewriteLoadBalancerClient(String serviceName, URI uri, TransportClient client) { _serviceName = serviceName; _uri = uri; _client = new RewriteClient(client, new D2URIRewriter(uri)); debug(_log, "created rewrite client: ", this); } @Override public void restRequest(RestRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.restRequest(request, requestContext, wireAttrs, callback); } @Override public void streamRequest(StreamRequest request, RequestContext requestContext, Map wireAttrs, TransportCallback callback) { assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(request.getURI())); _client.streamRequest(request, requestContext, wireAttrs, callback); } @Override public void shutdown(Callback callback) { _client.shutdown(callback); } @Deprecated public TransportClient getWrappedClient() { return _client; } public TransportClient getDecoratedClient() { return _client; } @Override public URI getUri() { return _uri; } public String getServiceName() { return _serviceName; } @Override public String toString() { return "RewriteLoadBalancerClient [_serviceName=" + _serviceName + ", _uri=" + _uri + ", _wrappedClient=" + _client + "]"; } } |
data class | data class | t | t | t | 0 | 3201 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/d2/src/main/java/com/linkedin/d2/balancer/clients/RewriteLoadBalancerClient.java/#L41-L111 | 1 | 308 | 3201 | minor | ||
| 2672 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | blob, data class | t | t | t | blob | 0 | 15216 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 2672 | 15216 | minor | |
| 2122 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
data class | blob, data class, long method | t | t | f | blob, long method | data class | 0 | 13214 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 1 | 2122 | 13214 | minor |
| 1847 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12172 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 1847 | 12172 | minor | ||
| 5649 | {"response": "YES I found bad smells\nthe bad smells are:\n1. Long method\n2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future generateAutonomousDatabaseWallet( final GenerateAutonomousDatabaseWalletRequest request, final com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handler) { LOG.trace("Called async generateAutonomousDatabaseWallet"); final GenerateAutonomousDatabaseWalletRequest interceptedRequest = GenerateAutonomousDatabaseWalletConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = GenerateAutonomousDatabaseWalletConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse> transformer = GenerateAutonomousDatabaseWalletConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse> handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< GenerateAutonomousDatabaseWalletRequest, GenerateAutonomousDatabaseWalletResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, GenerateAutonomousDatabaseWalletResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.post( ib, interceptedRequest.getGenerateAutonomousDatabaseWalletDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | \n1. long method\n2. feature envy | t | t | f | long method | 0 | 11206 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-database/src/main/java/com/oracle/bmc/database/DatabaseAsyncClient.java/#L1700-L1793 | 2 | 5649 | 11206 | major | |
| 748 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class PartnerLinkRef extends OBase implements RValue, LValue, Serializable { public static final long serialVersionUID = -1L; private static final String PARTNERLINK = "partnerLink"; private static final String ISMYENDPOINTREFERENCE = "isMyEndpointReference"; @JsonCreator public PartnerLinkRef() { setIsMyEndpointReference(false); } public PartnerLinkRef(OProcess owner) { super(owner); setIsMyEndpointReference(false); } @JsonIgnore public boolean isIsMyEndpointReference() { Object o = fieldContainer.get(ISMYENDPOINTREFERENCE); return o == null ? false : (Boolean) o; } @JsonIgnore public OPartnerLink getPartnerLink() { Object o = fieldContainer.get(PARTNERLINK); return o == null ? null : (OPartnerLink) o; } // Must fit in a LValue even if it's not variable based @JsonIgnore public Variable getVariable() { return null; } public void setIsMyEndpointReference(boolean isMyEndpointReference) { fieldContainer.put(ISMYENDPOINTREFERENCE, isMyEndpointReference); } public void setPartnerLink(OPartnerLink partnerLink) { fieldContainer.put(PARTNERLINK, partnerLink); } public String toString() { return "{PLinkRef " + getPartnerLink() + "!" + isIsMyEndpointReference() + "}"; } } |
data class | long method, data class | t | t | t | long method | 0 | 7018 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-nobj/src/main/java/org/apache/ode/bpel/obj/OAssign.java/#L393-L437 | 1 | 748 | 7018 | major | |
| 502 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicated code 4. Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method. 5. Use of hardcoded values instead of constants or variables 6. Multiple return statements - can be simplified to one return statement outside of the switch statement 7. Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Switch statement3 Duplicated code4 Feature envy - code should be moved to the appropriate class instead of being implemented in the deserialize method 5 Use of hardcoded values instead of constants or variables6 Multiple return statements - can be simplified to one return statement outside of the switch statement7 Code repetition, specifically in the switch cases for creating the different distributions and performing validation checks 8 Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting | t | f | t | specifically in the switch cases for creating the different distributions and performing validation checks. 8. Lack of proper error handling - the IllegalArgumentException is not specific and does not provide enough information for troubleshooting. | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 502 | 5087 | major | |
| 1575 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | Data Class | t | f | t | 0 | 11348 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 1575 | 11348 | minor | ||
| 347 | {"message": "YES, I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | blob, long method | t | t | f | blob | long method | 0 | 3549 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 347 | 3549 | major |
| 1635 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11522 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1635 | 11522 | minor | |
| 1628 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
blob | Blob, Data Class | t | f | t | Data Class | 0 | 11502 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 1628 | 11502 | minor | |
| 4044 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method, data class | t | t | t | data class | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 4044 | 10690 | critical | |
| 757 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7057 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 757 | 7057 | major | |
| 2524 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LivePropertySource { private final List properties; private final String sourceName; public LivePropertySource(String sourceName, List properties) { this.sourceName = sourceName; this.properties = properties != null ? ImmutableList.copyOf(properties) : ImmutableList.of(); } public String getSourceName() { return this.sourceName; } public LiveProperty getProperty(String propertyName) { for (LiveProperty liveProperty : properties) { if (liveProperty.getProperty().equals(propertyName)) { return liveProperty; } } return null; } } |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 14719 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/liveproperties/LivePropertySource.java/#L17-L41 | 1 | 2524 | 14719 | minor | |
| 1152 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1152 | 10133 | minor | |
| 752 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 752 | 7035 | major | |
| 109 | {"output": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | data class | t | t | t | 0 | 1442 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 109 | 1442 | major | ||
| 2573 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 2573 | 14908 | minor | ||
| 2520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 2520 | 14709 | minor | ||
| 2297 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 2297 | 14024 | major | ||
| 2330 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14150 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 2330 | 14150 | minor | |
| 1269 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | long method | t | t | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1269 | 10565 | minor | ||
| 885 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 885 | 8053 | minor | |
| 1734 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1734 | 11823 | major | ||
| 1322 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1322 | 10699 | major | ||
| 2041 | YES, I found bad smells. The bad smells are: 1. Feature envy: the methods within the GridMBeanServerData class are mostly only accessing and manipulating data within that class, which suggests that these methods should be moved into the class itself to avoid feature envy. 2. Long method: the GridMBeanServerData constructor, while not excessively long, could still benefit from being broken down into smaller methods for clarity and maintainability. 3. Magic numbers: the value for the initial capacity in the HashSet creation is a magic number and should be given a descriptive variable name. 4. No encapsulation: the fields in the GridMBeanServerData class are set to public, which could lead to potential issues if these fields are accidentally manipulated by external classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | Feature envy: the methods within the GridMBeanServerData class are mostly only accessing and manipulating data within that class, which suggests that these methods should be moved into the class itself to avoid feature envy2 Long method: the GridMBeanServerData constructor, while not excessively long, could still benefit from being broken down into smaller methods for clarity and maintainability3 Magic numbers: the value for the initial capacity in the HashSet creation is a magic number and should be given a descriptive variable name4 No encapsulation: the fields in the GridMBeanServerData class are set to public, which could lead to potential issues if these fields are accidentally manipulated by external classes | t | f | t | which suggests that these methods should be moved into the class itself to avoid feature envy.2. Long method: the GridMBeanServerData constructor, while not excessively long, which could lead to potential issues if these fields are accidentally manipulated by external classes. | 0 | 12853 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 2 | 2041 | 12853 | minor | |
| 630 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class, long method | t | t | t | long method | 0 | 6286 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 630 | 6286 | critical | |
| 1927 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Inappropriate commenting 4. Strong dependency (the method relies on the state of external variables) 5. Potential concurrency issues due to locking and unlocking of the sync mode | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
feature envy | Long method2 Feature envy3 Inappropriate commenting4 Strong dependency (the method relies on the state of external variables)5 Potential concurrency issues due to locking and unlocking of the sync mode | t | f | t | 0 | 12439 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1927 | 12439 | minor | ||
| 1398 | YES I found bad smells. The bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 10855 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1398 | 10855 | minor | |
| 1997 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1997 | 12700 | major | ||
| 873 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 7982 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 1 | 873 | 7982 | major | |
| 2276 | { "output": "YES I found bad smells", "detected_bad_smells": { "1. Blob": "ObjectInFolderListImpl class might be a Blob code smell as it contains multiple fields and methods that operate on these fields", "2. Data Class": "ObjectInFolderListImpl class might be considered a Data Class since it mainly contains getters and setters for its fields" } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | 1. blob: objectinfolderlistimpl class might be a blob code smell as it contains multiple fields and methods that operate on these fields, 2. data class: objectinfolderlistimpl class might be considered a data class since it mainly contains getters and setters for its fields | t | t | t | 1. blob: objectinfolderlistimpl class might be a blob code smell as it contains multiple fields and methods that operate on these fields | 0 | 13775 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 2276 | 13775 | major | |
| 2796 | { "response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface Type { //~ Methods ------------------------------------------------------------------------------------------------------------------ /** * return the human readable name of the type. "object" is returned * for object type. * @return name of the type */ String getName(); } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 1230 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/heap/Type.java/#L52-L61 | 1 | 2796 | 1230 | minor | |
| 1972 | {"output": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | 1. long method | t | t | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 1 | 1972 | 12611 | minor | ||
| 2266 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | long method, data class | t | t | t | long method | 0 | 13732 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 2266 | 13732 | critical | |
| 2312 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Tower extends Item { private Fit fit; private String tubing; public static enum Fit { Custom, Exact, Universal } public Fit getFit() { return fit; } public void setFit(Fit fit) { this.fit = fit; } public String getTubing() { return tubing; } public void setTubing(String tubing) { this.tubing = tubing; } ; } |
data class | data class | t | t | t | 0 | 14102 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/webservice-inheritance/src/main/java/org/superbiz/inheritance/Tower.java/#L21-L50 | 1 | 2312 | 14102 | major | ||
| 3358 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected String getTableStatus( Statement sStatement ) throws SQLException { ResultSet statusResultSet = sStatement.executeQuery( "show table status" ); StringBuilder statusString = new StringBuilder(); int numColumns = statusResultSet.getMetaData().getColumnCount(); while ( statusResultSet.next() ) { statusString.append( "\n" ); for ( int i = 1; i <= numColumns; i++ ) { statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " [" + statusResultSet.getString( i ) + "] | " ); } } return statusString.toString(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6369 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/disk/jdbc/mysql/MySQLTableOptimizer.java/#L212-L228 | 2 | 3358 | 6369 | minor | ||
| 2900 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | blob | t | t | t | 0 | 2146 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L233896-L233981 | 1 | 2900 | 2146 | minor | ||
| 2032 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Strings { public static final String[] EMPTY_ARRAY = new String[0]; public static boolean equalsIgnoreWhitespace(String left, String right) { String l = left == null ? "" : left.replaceAll("\\s", ""); String r = right == null ? "" : right.replaceAll("\\s", ""); return l.equals(r); } public static boolean equal(String literal, String name) { return isEmpty(literal) ? isEmpty(name) : literal.equals(name); } public static String notNull(Object o) { return String.valueOf(o); } public static String emptyIfNull(String s) { return (s == null) ? "" : s; } public static String concat(String separator, List list) { return concat(separator, list, 0); } public static String toString(Collection list, Function toString, String delim) { StringBuffer buffer = new StringBuffer(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { T t = iterator.next(); buffer.append(toString.apply(t)); if (iterator.hasNext()) buffer.append(delim); } return buffer.toString(); } public static String concat(String separator, List list, int skip) { StringBuffer buff = new StringBuffer(); int lastIndex = list.size() - skip; for (int i = 0; i < lastIndex; i++) { buff.append(list.get(i)); if (i + 1 < lastIndex) buff.append(separator); } String string = buff.toString(); return string.trim().length() == 0 ? null : string; } public static String skipLastToken(String value, String separator) { int endIndex = value.lastIndexOf(separator); if (endIndex > 0) return value.substring(0, endIndex); return value; } public static String lastToken(String value, String separator) { int index = value.lastIndexOf(separator) + separator.length(); if (index < value.length()) return value.substring(index, value.length()); return ""; } public static String toFirstUpper(String s) { if (s == null || s.length() == 0 || Character.isUpperCase(s.charAt(0))) return s; if (s.length() == 1) return s.toUpperCase(); return s.substring(0, 1).toUpperCase() + s.substring(1); } public static boolean isEmpty(String s) { return s == null || s.equals(""); } public static String newLine() { return System.getProperty("line.separator"); } /** * @since 2.13 */ public static String toPlatformLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", Strings.newLine()); } /** * @since 2.14 */ public static String toUnixLineSeparator(CharSequence cs) { return cs.toString().replaceAll("\r?\n", "\n"); } public static String toFirstLower(String s) { if (s == null || s.length() == 0 || Character.isLowerCase(s.charAt(0))) return s; if (s.length() == 1) return s.toLowerCase(); return s.substring(0, 1).toLowerCase() + s.substring(1); } private static final JavaStringConverter CONVERTER = new JavaStringConverter(); /** * Resolve Java control character sequences with to the actual character value. * Optionally handle unicode escape sequences, too. */ public static String convertFromJavaString(String string, boolean useUnicode) { return CONVERTER.convertFromJavaString(string, useUnicode); } /** * Escapes control characters with a preceding backslash. * Encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String theString) { return CONVERTER.convertToJavaString(theString, true); } /** * Escapes control characters with a preceding backslash. * Optionally encodes special chars as unicode escape sequence. * The resulting string is safe to be put into a Java string literal between * the quotes. */ public static String convertToJavaString(String input, boolean useUnicode) { return CONVERTER.convertToJavaString(input, useUnicode); } public static char toHex(int i) { return CONVERTER.toHex(i); } /** * Splits a string around matches of the given delimiter string. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * For delimiters of length 1 it is preferred to use {@link #split(String, char)} instead. * * @param value * the string to split * @param delimiter * the delimiting string (e.g. "::") * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} or {@code delimiter} is {@code null} */ public static List split(String value, String delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + delimiter.length(); index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } /** * Splits a string around matches of the given delimiter character. * * This method works similar to {@link String#split(String)} but does not treat the delimiter * as a regular expression. This makes it perform better in most cases where this feature is not * necessary. Furthermore this implies that trailing empty segments will not be part of the * result. * * @param value * the string to split * @param delimiter * the delimiting character (e.g. '.' or ':') * * @return the list of strings computed by splitting the string around matches of the given delimiter * without trailing empty segments. Never null and the list does not contain any null values. * * @throws NullPointerException * If the {@code value} is {@code null} * @see String#split(String) * @since 2.3 */ public static List split(String value, char delimiter) { List result = new ArrayList(); int lastIndex = 0; int index = value.indexOf(delimiter, lastIndex); int pendingEmptyStrings = 0; while (index != -1) { String addMe = value.substring(lastIndex, index); if (addMe.length() == 0) pendingEmptyStrings++; else { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(addMe); } lastIndex = index + 1; index = value.indexOf(delimiter, lastIndex); } if (lastIndex != value.length()) { while(pendingEmptyStrings > 0) { result.add(""); pendingEmptyStrings--; } result.add(value.substring(lastIndex)); } return result; } public static final char SEPARATOR = ':'; /** * @param strings array of strings, may not be null and may not contain any null values. * @throws NullPointerException if the array of strings or any element in the array is null */ public static String pack(String[] strings) { if (strings != null && strings.length > 0) { StringBuffer buffer = new StringBuffer(); for (String s : strings) { buffer.append(s.length()); buffer.append(SEPARATOR); buffer.append(s); } return buffer.toString(); } return null; } public static String[] unpack(String packed) { if (isEmpty(packed)) { return null; } else { List strings = Lists.newArrayList(); unpack(strings, packed); return strings.toArray(new String[strings.size()]); } } private static void unpack(List strings, String packed) { int delimiterIndex = packed.indexOf(":"); int size = Integer.parseInt(packed.substring(0, delimiterIndex)); int endIndex = delimiterIndex + 1 + size; strings.add(packed.substring(delimiterIndex + 1, endIndex)); if (endIndex < packed.length()) { unpack(strings, packed.substring(endIndex)); } } public static String removeLeadingWhitespace(String indentationString) { int i = 0; while (i 1 && s.charAt(s.length() - 2) == '\r') { return s.subSequence(0, s.length() - 2); } return s.subSequence(0, s.length() - 1); } if (s.charAt(s.length() - 1) == '\r') { return s.subSequence(0, s.length() - 1); } return s; } /** * Counts the number of lines where {@link #separator} is assumed to be the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text) { return countLines(text, separator); } /** * Counts the number of lines where the given separator sequence is the only valid line break sequence. * A string without any line separators returns {@code 0} as the number of lines. */ public static int countLines(String text, char[] separator) { return countLines(text, separator, 0, text.length()); } /** * Counts the number of lines between {@code startInclusive} and {@code endExclusive} * where the given separator sequence is the only valid line break sequence. * A string without any line separators in that range returns {@code 0} as the number of lines. * * @since 2.9 */ public static int countLines(String text, char[] separator, int startInclusive, int endExclusive) { int line = 0; if (separator.length == 1) { char c = separator[0]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c) { line++; } } } else if (separator.length == 2) { char c1 = separator[0]; char c2 = separator[1]; for (int i = startInclusive; i < endExclusive; i++) { if (text.charAt(i) == c1 && endExclusive > i + 1 && text.charAt(i + 1) == c2) { line++; i++; } else if (text.charAt(i) == c2) { line++; } } } else { throw new IllegalArgumentException("Separators with more than two characters are unexpected"); } return line; } // TODO is it worthwhile to deprecate this method and fix the typo 'Whitespace'? public static String getLeadingWhiteSpace(String original) { for(int i=0; i < original.length(); i++) { if (!Character.isWhitespace(original.charAt(i))) { return original.substring(0, i); } } return original; } /** * @since 2.1 */ public static String wordWrap(String string, int maxCharsPerLine) { StringBuilder document = new StringBuilder(); StringBuilder line = new StringBuilder(); StringBuilder word = new StringBuilder(); StringBuilder ws = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\n') { line.append(ws); line.append(word); line.append("\n"); document.append(line); line = new StringBuilder(); word = new StringBuilder(); ws = new StringBuilder(); } else if (Character.isWhitespace(c)) { if (line.length() + word.length() + 1 > maxCharsPerLine) { line.append("\n"); document.append(line); line = new StringBuilder(); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } else if (word.length() == 0) { ws.append(c); } else { line.append(ws); line.append(word); word = new StringBuilder(); ws = new StringBuilder(); ws.append(c); } } else { word.append(c); } } if (line.length() + word.length() + 1 > maxCharsPerLine) { document.append(line); document.append("\n"); document.append(word); } else { document.append(line); document.append(ws); document.append(word); } return document.toString(); } } |
blob | blob, long method | t | t | t | long method | 0 | 12819 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Strings.java/#L23-L475 | 1 | 2032 | 12819 | minor | |
| 1172 | {"output": "YES I found bad smells\nthe bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1172 | 10197 | critical | ||
| 2489 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
data class | data class, long method | t | t | t | long method | 0 | 14615 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 2489 | 14615 | minor | |
| 1388 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1388 | 10839 | critical | |
| 834 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public abstract class LFOAbstractType { protected int field_1_lsid; protected int field_2_unused1; protected int field_3_unused2; protected byte field_4_clfolvl; protected byte field_5_ibstFltAutoNum; protected Grfhic field_6_grfhic; protected byte field_7_unused3; protected LFOAbstractType() { this.field_6_grfhic = new Grfhic(); } protected void fillFields( byte[] data, int offset ) { field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); field_4_clfolvl = data[ 0xc + offset ]; field_5_ibstFltAutoNum = data[ 0xd + offset ]; field_6_grfhic = new Grfhic( data, 0xe + offset ); field_7_unused3 = data[ 0xf + offset ]; } public void serialize( byte[] data, int offset ) { LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); data[ 0xc + offset ] = field_4_clfolvl; data[ 0xd + offset ] = field_5_ibstFltAutoNum; field_6_grfhic.serialize( data, 0xe + offset ); data[ 0xf + offset ] = field_7_unused3; } public byte[] serialize() { final byte[] result = new byte[ getSize() ]; serialize( result, 0 ); return result; } /** * Size of record */ public static int getSize() { return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; LFOAbstractType other = (LFOAbstractType) obj; if ( field_1_lsid != other.field_1_lsid ) return false; if ( field_2_unused1 != other.field_2_unused1 ) return false; if ( field_3_unused2 != other.field_3_unused2 ) return false; if ( field_4_clfolvl != other.field_4_clfolvl ) return false; if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) return false; if ( field_6_grfhic == null ) { if ( other.field_6_grfhic != null ) return false; } else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) return false; if ( field_7_unused3 != other.field_7_unused3 ) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + field_1_lsid; result = prime * result + field_2_unused1; result = prime * result + field_3_unused2; result = prime * result + field_4_clfolvl; result = prime * result + field_5_ibstFltAutoNum; result = prime * result + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); result = prime * result + field_7_unused3; return result; } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[LFO]\n"); builder.append( " .lsid = " ); builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); builder.append( " .unused1 = " ); builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); builder.append( " .unused2 = " ); builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); builder.append( " .clfolvl = " ); builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); builder.append( " .ibstFltAutoNum = " ); builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); builder.append( " .grfhic = " ); builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); builder.append( " .unused3 = " ); builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); builder.append("[/LFO]"); return builder.toString(); } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public int getLsid() { return field_1_lsid; } /** * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. */ @Internal public void setLsid( int field_1_lsid ) { this.field_1_lsid = field_1_lsid; } /** * This field MUST be ignored. */ @Internal public int getUnused1() { return field_2_unused1; } /** * This field MUST be ignored. */ @Internal public void setUnused1( int field_2_unused1 ) { this.field_2_unused1 = field_2_unused1; } /** * This field MUST be ignored. */ @Internal public int getUnused2() { return field_3_unused2; } /** * This field MUST be ignored. */ @Internal public void setUnused2( int field_3_unused2 ) { this.field_3_unused2 = field_3_unused2; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public byte getClfolvl() { return field_4_clfolvl; } /** * An unsigned integer that specifies the field that this LFO represents.. */ @Internal public void setClfolvl( byte field_4_clfolvl ) { this.field_4_clfolvl = field_4_clfolvl; } /** * Used for AUTONUM field emulation. */ @Internal public byte getIbstFltAutoNum() { return field_5_ibstFltAutoNum; } /** * Used for AUTONUM field emulation. */ @Internal public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) { this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; } /** * HTML compatibility flags. */ @Internal public Grfhic getGrfhic() { return field_6_grfhic; } /** * HTML compatibility flags. */ @Internal public void setGrfhic( Grfhic field_6_grfhic ) { this.field_6_grfhic = field_6_grfhic; } /** * This field MUST be ignored. */ @Internal public byte getUnused3() { return field_7_unused3; } /** * This field MUST be ignored. */ @Internal public void setUnused3( byte field_7_unused3 ) { this.field_7_unused3 = field_7_unused3; } } // END OF CLASS |
data class | data class | t | t | t | 0 | 7749 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java/#L38-L290 | 1 | 834 | 7749 | major | ||
| 1394 | YES I found bad smells. The detected bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10850 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1394 | 10850 | major | ||
| 2258 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | data class | t | t | t | 0 | 13695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 1 | 2258 | 13695 | minor | ||
| 1429 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10951 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 1429 | 10951 | major | ||
| 1502 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Code duplication 4. Inconsistent naming conventions 5. Complex conditional statements 6. Nested loops 7. Unnecessary try-catch blocks 8. Inadequate exception handling 9. Inconsistent indentation and formatting 10. Poor variable naming 11. Code comments that are unclear or obsolete 12. Lack of modularity and separation of concerns 13. Too many responsibilities for a single method 14. Use of outdated Java language features | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Code duplication4 Inconsistent naming conventions5 Complex conditional statements6 Nested loops7 Unnecessary try-catch blocks8 Inadequate exception handling9 Inconsistent indentation and formatting | t | f | t | 0 | 11135 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 1502 | 11135 | critical | ||
| 1501 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11134 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 1501 | 11134 | minor | ||
| 5148 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 14405 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 5148 | 14405 | minor | ||
| 961 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | long method | t | t | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 961 | 8569 | minor | ||
| 676 | { "response": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SchemaAndValue { private final Schema schema; private final Object value; public static final SchemaAndValue NULL = new SchemaAndValue(null, null); public SchemaAndValue(Schema schema, Object value) { this.value = value; this.schema = schema; } public Schema schema() { return schema; } public Object value() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SchemaAndValue that = (SchemaAndValue) o; return Objects.equals(schema, that.schema) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(schema, value); } @Override public String toString() { return "SchemaAndValue{" + "schema=" + schema + ", value=" + value + '}'; } } |
data class | blob, data class | t | t | t | blob | 0 | 6576 | https://github.com/apache/kafka/blob/c74acb24eb1da5d16cc2721a63931cd87f79ec66/connect/api/src/main/java/org/apache/kafka/connect/data/SchemaAndValue.java/#L21-L61 | 1 | 676 | 6576 | minor | |
| 1647 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Inefficient looping 5. Inconsistent naming conventions 6. Lack of encapsulation/modularity 7. Inconsistent use of synchronized blocks 8. Complex conditional statements within loops 9. Use of break/continue statements 10. Lack of proper commenting/documentation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | Long method2 Feature envy3 Primitive obsession4 Inefficient looping5 Inconsistent naming conventions 6 Lack of encapsulation/modularity 7 Inconsistent use of synchronized blocks 8 Complex conditional statements within loops 9 Use of break/continue statements | t | f | t | 0 | 11563 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1647 | 11563 | critical | ||
| 2542 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | data class | t | t | t | 0 | 14785 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 1 | 2542 | 14785 | minor | ||
| 731 | YES I found bad smells the bad smells are: 1. Long method 2. Indentation smell 3. Inconsistent formatting 4. Use of switch statement 5. Nested control structures 6. Feature envy 7. Lack of comments/documentation 8. Confusing variable/parameter names 9. Potentially inefficient use of method chaining (searchStrings and toLowerCase) 10. Lack of code reusability/modularity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | Long method2 Indentation smell3 Inconsistent formatting4 Use of switch statement5 Nested control structures6 Feature envy7 Lack of comments/documentation8 Confusing variable/parameter names9 Potentially inefficient use of method chaining (searchStrings and toLowerCase) | t | f | t | 0 | 6879 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 731 | 6879 | minor | ||
| 4086 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Switch statement with multiple cases 4. Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5. Multiple nested if statements 6. Use of input.LA() and input.index() methods multiple times 7. Use of input.rewind() method multiple times 8. Lack of proper naming conventions for variables and methods 9. Duplicate code within cases 1 and 2 10. Unclear and confusing method description and functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy3 Switch statement with multiple cases4 Use of synpred33_InternalXbaseWithAnnotations() method for multiple if conditions 5 Multiple nested if statements 6 Use of inputLA() and inputindex() methods multiple times 7 Use of inputrewind() method multiple times 8 Lack of proper naming conventions for variables and methods 9 Duplicate code within cases | t | f | t | 0 | 10775 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 4086 | 10775 | major | ||
| 1817 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1817 | 12088 | minor | |
| 1897 | "Yes, I found bad smells. The bad smells are: Feature envy, long method." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | Feature envy, long method" | t | f | t | Feature envy | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 1897 | 12341 | minor | |
| 1463 | {"response":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | data class, long method | t | t | t | long method | 0 | 11027 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 1463 | 11027 | major | |
| 579 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method, data class | t | t | t | data class | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 579 | 5784 | major | |
| 2506 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | long method, data class | t | t | t | long method | 0 | 14669 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 2506 | 14669 | major | |
| 1670 | {"output": "YES I found bad smells the bad smells are: \n1. Blob, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
blob | \n1. blob, 2. data class | t | t | t | 2. data class | 0 | 11632 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 1 | 1670 | 11632 | minor | |
| 2084 | YES, I found bad smells the bad smells are: 1. Long data class, 2. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | Long data class, 2 Primitive obsession | t | f | t | 2. Primitive obsession | 0 | 13082 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 2 | 2084 | 13082 | major | |
| 3913 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10244 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 3913 | 10244 | minor | ||
| 1590 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 1590 | 11387 | minor | ||
| 4088 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | long method | t | t | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 1 | 4088 | 10777 | minor | ||
| 5713 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5713 | 12782 | critical | |
| 556 | YES, bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Optional removeUncomparableFieldsFromRecord(Schema record, Set processed) { Preconditions.checkArgument(record.getType() == Schema.Type.RECORD); if (processed.contains(record)) { return Optional.absent(); } processed.add(record); List fields = Lists.newArrayList(); for (Field field : record.getFields()) { Optional newFieldSchema = removeUncomparableFields(field.schema(), processed); if (newFieldSchema.isPresent()) { fields.add(new Field(field.name(), newFieldSchema.get(), field.doc(), field.defaultValue())); } } Schema newSchema = Schema.createRecord(record.getName(), record.getDoc(), record.getNamespace(), false); newSchema.setFields(fields); return Optional.of(newSchema); } |
feature envy | Long Method2 Feature Envy | t | f | t | 0 | 5609 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java/#L615-L634 | 2 | 556 | 5609 | major | ||
| 123 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public QMUIAlphaImageButton addRightImageButton(int drawableResId, int viewId) { return mTopBar.addRightImageButton(drawableResId, viewId); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1542 | https://github.com/Tencent/QMUI_Android/blob/6ff5493a05845918c126cce8a3e639f8d996481b/qmui/src/main/java/com/qmuiteam/qmui/widget/QMUITopBarLayout.java/#L136-L138 | 2 | 123 | 1542 | major | |
| 1076 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Commented out code 4. Hard-coded string values 5. Nested looping 6. Duplicate code 7. Use of mutable data types without proper synchronization | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Commented out code4 Hard-coded string values5 Nested looping6 Duplicate code7 Use of mutable data types without proper synchronization | t | f | t | 0 | 9643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1076 | 9643 | major | ||
| 119 | { "message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 119 | 1514 | major | |
| 2042 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | 1. long method | t | t | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 2042 | 12854 | major | ||
| 316 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | feature envy | t | t | t | 0 | 3247 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 1 | 316 | 3247 | critical | ||
| 4181 | YES I found bad smells. The bad smells are: 1. Long method 2. Magic number (the use of specific numbers without explanation) 3. Duplicate code (the repeated switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | Long method2 Magic number (the use of specific numbers without explanation)3 Duplicate code (the repeated switch statement) | t | f | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 2 | 4181 | 11002 | minor | ||
| 2094 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent spacing and formatting 4. Multiple parameters in method signature 5. Mixing of different responsibilities (writing JSON, getting services, parsing status line) 6. Lack of use of constants for repeated strings (e.g. "data", "serviceCount", "status") 7. Potentially inefficient use of for loop when iterating over services array 8. Nested if statement with multiple conditions 9. Missing error handling for IOException 10. Indirect variable access (accessing Locale object through ServiceReference instead of passing directly) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | Long method2 Feature envy3 Inconsistent spacing and formatting4 Multiple parameters in method signature5 Mixing of different responsibilities (writing JSON, getting services, parsing status line)6 Lack of use of constants for repeated strings (eg "data", "serviceCount", "status")7 Potentially inefficient use of for loop when iterating over services array8 Nested if statement with multiple conditions 9 Missing error handling for IOException | t | f | t | getting services, parsing status line)6. Lack of use of constants for repeated strings (e.g. "data", "serviceCount", "status")7. Potentially inefficient use of for loop when iterating over services array8. Nested if statement with multiple conditions 9. Missing error handling for IOException | 0 | 13142 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 2094 | 13142 | minor | |
| 548 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5554 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 548 | 5554 | minor | ||
| 1580 | " YES I found bad smells" The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1580 | 11359 | critical | |
| 957 | YES I found bad smells the bad smells are: 1. Long method 2. Message chain 3. Large class 4. Feature envy 5. Data class 6. Primitive obsession 7. Duplicate code 8. Commented-out code 9. Inappropriate naming 10. Incomplete error handling 11. Inconsistent formatting 12. Use of raw types 13. Inefficient use of constructors 14. Overuse of getters and setters 15. Use of mutable fields | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
data class | Long method2 Message chain3 Large class4 Feature envy5 Data class6 Primitive obsession7 Duplicate code8 Commented-out code9 Inappropriate naming | t | f | t | 0 | 8546 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 2 | 957 | 8546 | major | ||
| 874 | {"answer": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JSAMDEmitter extends JSEmitter implements IJSAMDEmitter { private Map foundAccessors = new HashMap(); private int inheritenceLevel = -1; private ExportWriter exportWriter; private boolean initializingFieldsInConstructor; private List baseClassCalls = new ArrayList(); StringBuilder builder() { return getBuilder(); } IJSAMDDocEmitter getDoc() { return (IJSAMDDocEmitter) getDocEmitter(); } public JSAMDEmitter(FilterWriter out) { super(out); exportWriter = new ExportWriter(this); } @Override public void emitPackageHeader(IPackageDefinition definition) { // TODO (mschmalle|AMD) this is a hack but I know no other way to do replacements in a Writer setBufferWrite(true); write(JSAMDEmitterTokens.DEFINE); write(ASEmitterTokens.PAREN_OPEN); IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.addFrameworkDependencies(); exportWriter.addImports(type); exportWriter.queueExports(type, true); writeToken(ASEmitterTokens.COMMA); } @Override public void emitPackageHeaderContents(IPackageDefinition definition) { // nothing } @Override public void emitPackageContents(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; write("function($exports"); exportWriter.queueExports(type, false); write(") {"); indentPush(); writeNewline(); write("\"use strict\"; "); writeNewline(); ITypeNode tnode = findTypeNode(definition.getNode()); if (tnode != null) { getWalker().walk(tnode); // IClassNode | IInterfaceNode } indentPop(); writeNewline(); write("}"); // end returned function } @Override public void emitPackageFooter(IPackageDefinition definition) { IASScope containedScope = definition.getContainedScope(); ITypeDefinition type = findType(containedScope.getAllLocalDefinitions()); if (type == null) return; exportWriter.writeExports(type, true); exportWriter.writeExports(type, false); write(");"); // end define() // flush the buffer, writes the builder to out flushBuilder(); } private void emitConstructor(IFunctionNode node) { FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(getProblems()); //IFunctionDefinition definition = node.getDefinition(); write("function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); if (!isImplicit((IContainerNode) node.getScopedNode())) { emitMethodScope(node.getScopedNode()); } else { // we have a synthesized constructor, implict } } @Override public void emitInterface(IInterfaceNode node) { final IInterfaceDefinition definition = node.getDefinition(); final String interfaceName = definition.getBaseName(); write("AS3.interface_($exports, {"); indentPush(); writeNewline(); write("package_: \""); write(definition.getPackageName()); write("\","); writeNewline(); write("interface_: \""); write(interfaceName); write("\""); IReference[] references = definition.getExtendedInterfaceReferences(); final int len = references.length; if (len > 0) { writeNewline(); write("extends_: ["); indentPush(); writeNewline(); int i = 0; for (IReference reference : references) { write(reference.getName()); if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); writeNewline(); write("]"); } indentPop(); writeNewline(); write("});"); // end compilation unit } @Override public void emitClass(IClassNode node) { //ICompilerProject project = getWalker().getProject(); IClassDefinition definition = node.getDefinition(); getModel().setCurrentClass(definition); final String className = definition.getBaseName(); write("AS3.compilationUnit($exports, function($primaryDeclaration){"); indentPush(); writeNewline(); // write constructor emitConstructor((IFunctionNode) definition.getConstructor().getNode()); writeNewline(); // base class IReference baseClassReference = definition.getBaseClassReference(); boolean hasSuper = baseClassReference != null && !baseClassReference.getName().equals("Object"); if (hasSuper) { String baseName = baseClassReference.getName(); write("var Super = (" + baseName + "._ || " + baseName + "._$get());"); writeNewline(); write("var super$ = Super.prototype;"); writeNewline(); } write("$primaryDeclaration(AS3.class_({"); indentPush(); writeNewline(); // write out package write("package_: \"" + definition.getPackageName() + "\","); writeNewline(); // write class write("class_: \"" + definition.getBaseName() + "\","); writeNewline(); if (hasSuper) { write("extends_: Super,"); writeNewline(); } IReference[] references = definition .getImplementedInterfaceReferences(); int len = references.length; // write implements write("implements_:"); write(" ["); if (len > 0) { indentPush(); writeNewline(); } int i = 0; for (IReference reference : references) { write(reference.getName()); exportWriter.addDependency(reference.getName(), reference.getDisplayString(), false, false); if (i < len - 1) { write(","); writeNewline(); } i++; } if (len > 0) { indentPop(); writeNewline(); } write("],"); writeNewline(); // write members final IDefinitionNode[] members = node.getAllMemberNodes(); write("members: {"); indentPush(); writeNewline(); // constructor write("constructor: " + className); if (members.length > 0) { write(","); writeNewline(); } List instanceMembers = new ArrayList(); List staticMembers = new ArrayList(); List staticStatements = new ArrayList(); TempTools.fillInstanceMembers(members, instanceMembers); TempTools.fillStaticMembers(members, staticMembers, true, false); TempTools.fillStaticStatements(node, staticStatements, false); len = instanceMembers.size(); i = 0; for (IDefinitionNode mnode : instanceMembers) { if (mnode instanceof IAccessorNode) { if (foundAccessors.containsKey(mnode.getName())) { len--; continue; } getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } else { write(mnode.getName()); } if (i < len - 1) { write(","); writeNewline(); } i++; } // base class super calls len = baseClassCalls.size(); i = 0; if (len > 0) { write(","); writeNewline(); } for (IDefinition baseCall : baseClassCalls) { write(baseCall.getBaseName() + "$" + inheritenceLevel + ": super$." + baseCall.getBaseName()); if (i < len - 1) { write(","); writeNewline(); } } // end members indentPop(); writeNewline(); write("},"); writeNewline(); len = staticMembers.size(); write("staticMembers: {"); indentPush(); writeNewline(); i = 0; for (IDefinitionNode mnode : staticMembers) { if (mnode instanceof IAccessorNode) { // TODO (mschmalle|AMD) havn't taken care of static accessors if (foundAccessors.containsKey(mnode.getName())) continue; foundAccessors.put(mnode.getName(), mnode); getWalker().walk(mnode); } else if (mnode instanceof IFunctionNode) { getWalker().walk(mnode); } else if (mnode instanceof IVariableNode) { getWalker().walk(mnode); } if (i < len - 1) { write(","); writeNewline(); } i++; } indentPop(); if (len > 0) writeNewline(); write("}"); indentPop(); writeNewline(); write("}));"); // static statements len = staticStatements.size(); if (len > 0) writeNewline(); i = 0; for (IASNode statement : staticStatements) { getWalker().walk(statement); if (!(statement instanceof IBlockNode)) write(";"); if (i < len - 1) writeNewline(); i++; } indentPop(); writeNewline(); write("});"); // end compilation unit } //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- @Override public void emitField(IVariableNode node) { IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); if (definition.isStatic()) { IClassDefinition parent = (IClassDefinition) definition.getParent(); write(parent.getBaseName()); write("."); write(definition.getBaseName()); write(" = "); emitFieldInitialValue(node); return; } String name = toPrivateName(definition); write(name); write(": "); write("{"); indentPush(); writeNewline(); // field value write("value:"); emitFieldInitialValue(node); write(","); writeNewline(); // writable write("writable:"); write(!(definition instanceof IConstantDefinition) ? "true" : "false"); indentPop(); writeNewline(); write("}"); } private void emitFieldInitialValue(IVariableNode node) { ICompilerProject project = getWalker().getProject(); IVariableDefinition definition = (IVariableDefinition) node .getDefinition(); IExpressionNode valueNode = node.getAssignedValueNode(); if (valueNode != null) getWalker().walk(valueNode); else write(TempTools.toInitialValue(definition, project)); } @Override public void emitGetAccessor(IGetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition getter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition setter = getter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } @Override public void emitSetAccessor(ISetterNode node) { if (foundAccessors.containsKey(node.getName())) return; foundAccessors.put(node.getName(), node); ICompilerProject project = getWalker().getProject(); IAccessorDefinition setter = (IAccessorDefinition) node.getDefinition(); IAccessorDefinition getter = setter .resolveCorrespondingAccessor(project); emitGetterSetterPair(getter, setter); } private void emitGetterSetterPair(IAccessorDefinition getter, IAccessorDefinition setter) { write(getter.getBaseName()); write(": {"); indentPush(); writeNewline(); if (getter != null) { emitAccessor("get", getter); } if (setter != null) { write(","); writeNewline(); emitAccessor("set", setter); } indentPop(); writeNewline(); write("}"); } protected void emitAccessor(String kind, IAccessorDefinition definition) { IFunctionNode fnode = definition.getFunctionNode(); FunctionNode fn = (FunctionNode) fnode; fn.parseFunctionBody(new ArrayList()); write(kind + ": function "); write(definition.getBaseName() + "$" + kind); emitParameters(fnode.getParametersContainerNode()); emitMethodScope(fnode.getScopedNode()); } @Override public void emitMethod(IFunctionNode node) { if (node.isConstructor()) { emitConstructor(node); return; } FunctionNode fn = (FunctionNode) node; fn.parseFunctionBody(new ArrayList()); IFunctionDefinition definition = node.getDefinition(); String name = toPrivateName(definition); write(name); write(":"); write(" function "); write(node.getName()); emitParameters(node.getParametersContainerNode()); emitMethodScope(node.getScopedNode()); } @Override public void emitFunctionBlockHeader(IFunctionNode node) { IFunctionDefinition definition = node.getDefinition(); if (node.isConstructor()) { initializingFieldsInConstructor = true; IClassDefinition type = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); // emit public fields init values List fields = TempTools.getFields(type, true); for (IVariableDefinition field : fields) { if (TempTools.isVariableAParameter(field, definition.getParameters())) continue; write("this."); write(field.getBaseName()); write(" = "); emitFieldInitialValue((IVariableNode) field.getNode()); write(";"); writeNewline(); } initializingFieldsInConstructor = false; } emitDefaultParameterCodeBlock(node); } private void emitDefaultParameterCodeBlock(IFunctionNode node) { // TODO (mschmalle|AMD) test for ... rest // if default parameters exist, produce the init code IParameterNode[] pnodes = node.getParameterNodes(); Map defaults = TempTools.getDefaults(pnodes); if (pnodes.length == 0) return; if (defaults != null) { boolean hasBody = node.getScopedNode().getChildCount() > 0; if (!hasBody) { indentPush(); write(ASEmitterTokens.INDENT); } final StringBuilder code = new StringBuilder(); List parameters = new ArrayList( defaults.values()); Collections.reverse(parameters); int len = defaults.size(); // make the header in reverse order for (IParameterNode pnode : parameters) { if (pnode != null) { code.setLength(0); code.append(ASEmitterTokens.IF.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.PAREN_OPEN.getToken()); code.append(JSEmitterTokens.ARGUMENTS.getToken()); code.append(ASEmitterTokens.MEMBER_ACCESS.getToken()); code.append(JSAMDEmitterTokens.LENGTH.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.LESS_THAN.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(len); code.append(ASEmitterTokens.PAREN_CLOSE.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.BLOCK_OPEN.getToken()); write(code.toString()); indentPush(); writeNewline(); } len--; } Collections.reverse(parameters); for (int i = 0, n = parameters.size(); i < n; i++) { IParameterNode pnode = parameters.get(i); if (pnode != null) { code.setLength(0); code.append(pnode.getName()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(ASEmitterTokens.EQUAL.getToken()); code.append(ASEmitterTokens.SPACE.getToken()); code.append(pnode.getDefaultValue()); code.append(ASEmitterTokens.SEMICOLON.getToken()); write(code.toString()); indentPop(); writeNewline(); write(ASEmitterTokens.BLOCK_CLOSE); if (i == n - 1 && !hasBody) indentPop(); writeNewline(); } } } } @Override public void emitParameter(IParameterNode node) { getWalker().walk(node.getNameExpressionNode()); } @Override public void emitMemberAccessExpression(IMemberAccessExpressionNode node) { getWalker().walk(node.getLeftOperandNode()); if (!(node.getLeftOperandNode() instanceof ILanguageIdentifierNode)) write(node.getOperator().getOperatorText()); getWalker().walk(node.getRightOperandNode()); } @Override public void emitFunctionCall(IFunctionCallNode node) { if (node.isNewExpression()) { write(ASEmitterTokens.NEW); write(ASEmitterTokens.SPACE); } // IDefinition resolve = node.resolveType(project); // if (NativeUtils.isNative(resolve.getBaseName())) // { // // } getWalker().walk(node.getNameNode()); emitArguments(node.getArgumentsNode()); } @Override public void emitArguments(IContainerNode node) { IContainerNode newNode = node; FunctionCallNode fnode = (FunctionCallNode) node.getParent(); if (TempTools.injectThisArgument(fnode, false)) { IdentifierNode thisNode = new IdentifierNode("this"); newNode = EmitterUtils.insertArgumentsBefore(node, thisNode); } int len = newNode.getChildCount(); write(ASEmitterTokens.PAREN_OPEN); for (int i = 0; i < len; i++) { IExpressionNode inode = (IExpressionNode) newNode.getChild(i); if (inode.getNodeID() == ASTNodeID.IdentifierID) { emitArgumentIdentifier((IIdentifierNode) inode); } else { getWalker().walk(inode); } if (i < len - 1) { writeToken(ASEmitterTokens.COMMA); } } write(ASEmitterTokens.PAREN_CLOSE); } private void emitArgumentIdentifier(IIdentifierNode node) { ITypeDefinition type = node.resolveType(getWalker().getProject()); if (type instanceof ClassTraitsDefinition) { String qualifiedName = type.getQualifiedName(); write(qualifiedName); } else { // XXX A problem? getWalker().walk(node); } } @Override public void emitIdentifier(IIdentifierNode node) { ICompilerProject project = getWalker().getProject(); IDefinition resolve = node.resolve(project); if (TempTools.isBinding(node, project)) { // AS3.bind( this,"secret$1"); // this will happen on the right side of the = sign to bind a methof/function // to a variable write("AS3.bind(this, \"" + toPrivateName(resolve) + "\")"); } else { IExpressionNode leftBase = TempTools.getNode(node, false, project); if (leftBase == node) { if (TempTools.isValidThis(node, project)) write("this."); // in constructor and a type if (initializingFieldsInConstructor && resolve instanceof IClassDefinition) { String name = resolve.getBaseName(); write("(" + name + "._ || " + name + "._$get())"); return; } } if (resolve != null) { // TODO (mschmalle|AMD) optimize String name = toPrivateName(resolve); if (NativeUtils.isNative(name)) exportWriter.addDependency(name, name, true, false); if (node.getParent() instanceof IMemberAccessExpressionNode) { IMemberAccessExpressionNode mnode = (IMemberAccessExpressionNode) node .getParent(); if (mnode.getLeftOperandNode().getNodeID() == ASTNodeID.SuperID) { IIdentifierNode lnode = (IIdentifierNode) mnode .getRightOperandNode(); IClassNode cnode = (IClassNode) node .getAncestorOfType(IClassNode.class); initializeInheritenceLevel(cnode.getDefinition()); // super.foo(); write("this."); write(lnode.getName() + "$" + inheritenceLevel); baseClassCalls.add(resolve); return; } } write(name); } else { // no definition, just plain ole identifer write(node.getName()); } } } @Override protected void emitType(IExpressionNode node) { } @Override public void emitLanguageIdentifier(ILanguageIdentifierNode node) { if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.ANY_TYPE) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.REST) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.SUPER) { IIdentifierNode inode = (IIdentifierNode) node; if (inode.getParent() instanceof IMemberAccessExpressionNode) { } else { write("Super.call"); } } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS) { write(""); } else if (node.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.VOID) { write(""); } } private String toPrivateName(IDefinition definition) { if (definition instanceof ITypeDefinition) return definition.getBaseName(); if (!definition.isPrivate()) return definition.getBaseName(); initializeInheritenceLevel(definition); return definition.getBaseName() + "$" + inheritenceLevel; } void initializeInheritenceLevel(IDefinition definition) { if (inheritenceLevel != -1) return; IClassDefinition cdefinition = null; if (definition instanceof IClassDefinition) cdefinition = (IClassDefinition) definition; else cdefinition = (IClassDefinition) definition .getAncestorOfType(IClassDefinition.class); ICompilerProject project = getWalker().getProject(); IClassDefinition[] ancestry = cdefinition.resolveAncestry(project); inheritenceLevel = ancestry.length - 1; } } |
blob | blob, long method | t | t | t | long method | 0 | 7998 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/js/amd/JSAMDEmitter.java/#L78-L971 | 1 | 874 | 7998 | critical | |
| 1562 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | Data Class | t | f | t | 0 | 11312 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 1562 | 11312 | minor | ||
| 4181 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | long method | t | t | t | 0 | 11002 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 4181 | 11002 | minor | ||
| 5343 | { "message": "YES I found bad smells", "the bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.12.0)") public class Assignment implements org.apache.storm.thrift.TBase, java.io.Serializable, Cloneable, Comparable { private static final org.apache.storm.thrift.protocol.TStruct STRUCT_DESC = new org.apache.storm.thrift.protocol.TStruct("Assignment"); private static final org.apache.storm.thrift.protocol.TField MASTER_CODE_DIR_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("master_code_dir", org.apache.storm.thrift.protocol.TType.STRING, (short)1); private static final org.apache.storm.thrift.protocol.TField NODE_HOST_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("node_host", org.apache.storm.thrift.protocol.TType.MAP, (short)2); private static final org.apache.storm.thrift.protocol.TField EXECUTOR_NODE_PORT_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("executor_node_port", org.apache.storm.thrift.protocol.TType.MAP, (short)3); private static final org.apache.storm.thrift.protocol.TField EXECUTOR_START_TIME_SECS_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("executor_start_time_secs", org.apache.storm.thrift.protocol.TType.MAP, (short)4); private static final org.apache.storm.thrift.protocol.TField WORKER_RESOURCES_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("worker_resources", org.apache.storm.thrift.protocol.TType.MAP, (short)5); private static final org.apache.storm.thrift.protocol.TField TOTAL_SHARED_OFF_HEAP_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("total_shared_off_heap", org.apache.storm.thrift.protocol.TType.MAP, (short)6); private static final org.apache.storm.thrift.protocol.TField OWNER_FIELD_DESC = new org.apache.storm.thrift.protocol.TField("owner", org.apache.storm.thrift.protocol.TType.STRING, (short)7); private static final org.apache.storm.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new AssignmentStandardSchemeFactory(); private static final org.apache.storm.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new AssignmentTupleSchemeFactory(); private @org.apache.storm.thrift.annotation.Nullable java.lang.String master_code_dir; // required private @org.apache.storm.thrift.annotation.Nullable java.util.Map node_host; // optional private @org.apache.storm.thrift.annotation.Nullable java.util.Map,NodeInfo> executor_node_port; // optional private @org.apache.storm.thrift.annotation.Nullable java.util.Map,java.lang.Long> executor_start_time_secs; // optional private @org.apache.storm.thrift.annotation.Nullable java.util.Map worker_resources; // optional private @org.apache.storm.thrift.annotation.Nullable java.util.Map total_shared_off_heap; // optional private @org.apache.storm.thrift.annotation.Nullable java.lang.String owner; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.storm.thrift.TFieldIdEnum { MASTER_CODE_DIR((short)1, "master_code_dir"), NODE_HOST((short)2, "node_host"), EXECUTOR_NODE_PORT((short)3, "executor_node_port"), EXECUTOR_START_TIME_SECS((short)4, "executor_start_time_secs"), WORKER_RESOURCES((short)5, "worker_resources"), TOTAL_SHARED_OFF_HEAP((short)6, "total_shared_off_heap"), OWNER((short)7, "owner"); private static final java.util.Map byName = new java.util.HashMap(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.storm.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // MASTER_CODE_DIR return MASTER_CODE_DIR; case 2: // NODE_HOST return NODE_HOST; case 3: // EXECUTOR_NODE_PORT return EXECUTOR_NODE_PORT; case 4: // EXECUTOR_START_TIME_SECS return EXECUTOR_START_TIME_SECS; case 5: // WORKER_RESOURCES return WORKER_RESOURCES; case 6: // TOTAL_SHARED_OFF_HEAP return TOTAL_SHARED_OFF_HEAP; case 7: // OWNER return OWNER; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.storm.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.NODE_HOST,_Fields.EXECUTOR_NODE_PORT,_Fields.EXECUTOR_START_TIME_SECS,_Fields.WORKER_RESOURCES,_Fields.TOTAL_SHARED_OFF_HEAP,_Fields.OWNER}; public static final java.util.Map<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.storm.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.MASTER_CODE_DIR, new org.apache.storm.thrift.meta_data.FieldMetaData("master_code_dir", org.apache.storm.thrift.TFieldRequirementType.REQUIRED, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.NODE_HOST, new org.apache.storm.thrift.meta_data.FieldMetaData("node_host", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING), new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.EXECUTOR_NODE_PORT, new org.apache.storm.thrift.meta_data.FieldMetaData("executor_node_port", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP, new org.apache.storm.thrift.meta_data.ListMetaData(org.apache.storm.thrift.protocol.TType.LIST, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.I64)), new org.apache.storm.thrift.meta_data.StructMetaData(org.apache.storm.thrift.protocol.TType.STRUCT, NodeInfo.class)))); tmpMap.put(_Fields.EXECUTOR_START_TIME_SECS, new org.apache.storm.thrift.meta_data.FieldMetaData("executor_start_time_secs", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP, new org.apache.storm.thrift.meta_data.ListMetaData(org.apache.storm.thrift.protocol.TType.LIST, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.I64)), new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.I64)))); tmpMap.put(_Fields.WORKER_RESOURCES, new org.apache.storm.thrift.meta_data.FieldMetaData("worker_resources", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP, new org.apache.storm.thrift.meta_data.StructMetaData(org.apache.storm.thrift.protocol.TType.STRUCT, NodeInfo.class), new org.apache.storm.thrift.meta_data.StructMetaData(org.apache.storm.thrift.protocol.TType.STRUCT, WorkerResources.class)))); tmpMap.put(_Fields.TOTAL_SHARED_OFF_HEAP, new org.apache.storm.thrift.meta_data.FieldMetaData("total_shared_off_heap", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.MapMetaData(org.apache.storm.thrift.protocol.TType.MAP, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING), new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.DOUBLE)))); tmpMap.put(_Fields.OWNER, new org.apache.storm.thrift.meta_data.FieldMetaData("owner", org.apache.storm.thrift.TFieldRequirementType.OPTIONAL, new org.apache.storm.thrift.meta_data.FieldValueMetaData(org.apache.storm.thrift.protocol.TType.STRING))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.storm.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Assignment.class, metaDataMap); } public Assignment() { this.node_host = new java.util.HashMap(); this.executor_node_port = new java.util.HashMap,NodeInfo>(); this.executor_start_time_secs = new java.util.HashMap,java.lang.Long>(); this.worker_resources = new java.util.HashMap(); this.total_shared_off_heap = new java.util.HashMap(); } public Assignment( java.lang.String master_code_dir) { this(); this.master_code_dir = master_code_dir; } /** * Performs a deep copy on other. */ public Assignment(Assignment other) { if (other.is_set_master_code_dir()) { this.master_code_dir = other.master_code_dir; } if (other.is_set_node_host()) { java.util.Map __this__node_host = new java.util.HashMap(other.node_host); this.node_host = __this__node_host; } if (other.is_set_executor_node_port()) { java.util.Map,NodeInfo> __this__executor_node_port = new java.util.HashMap,NodeInfo>(other.executor_node_port.size()); for (java.util.Map.Entry, NodeInfo> other_element : other.executor_node_port.entrySet()) { java.util.List other_element_key = other_element.getKey(); NodeInfo other_element_value = other_element.getValue(); java.util.List __this__executor_node_port_copy_key = new java.util.ArrayList(other_element_key); NodeInfo __this__executor_node_port_copy_value = new NodeInfo(other_element_value); __this__executor_node_port.put(__this__executor_node_port_copy_key, __this__executor_node_port_copy_value); } this.executor_node_port = __this__executor_node_port; } if (other.is_set_executor_start_time_secs()) { java.util.Map,java.lang.Long> __this__executor_start_time_secs = new java.util.HashMap,java.lang.Long>(other.executor_start_time_secs.size()); for (java.util.Map.Entry, java.lang.Long> other_element : other.executor_start_time_secs.entrySet()) { java.util.List other_element_key = other_element.getKey(); java.lang.Long other_element_value = other_element.getValue(); java.util.List __this__executor_start_time_secs_copy_key = new java.util.ArrayList(other_element_key); java.lang.Long __this__executor_start_time_secs_copy_value = other_element_value; __this__executor_start_time_secs.put(__this__executor_start_time_secs_copy_key, __this__executor_start_time_secs_copy_value); } this.executor_start_time_secs = __this__executor_start_time_secs; } if (other.is_set_worker_resources()) { java.util.Map __this__worker_resources = new java.util.HashMap(other.worker_resources.size()); for (java.util.Map.Entry other_element : other.worker_resources.entrySet()) { NodeInfo other_element_key = other_element.getKey(); WorkerResources other_element_value = other_element.getValue(); NodeInfo __this__worker_resources_copy_key = new NodeInfo(other_element_key); WorkerResources __this__worker_resources_copy_value = new WorkerResources(other_element_value); __this__worker_resources.put(__this__worker_resources_copy_key, __this__worker_resources_copy_value); } this.worker_resources = __this__worker_resources; } if (other.is_set_total_shared_off_heap()) { java.util.Map __this__total_shared_off_heap = new java.util.HashMap(other.total_shared_off_heap); this.total_shared_off_heap = __this__total_shared_off_heap; } if (other.is_set_owner()) { this.owner = other.owner; } } public Assignment deepCopy() { return new Assignment(this); } @Override public void clear() { this.master_code_dir = null; this.node_host = new java.util.HashMap(); this.executor_node_port = new java.util.HashMap,NodeInfo>(); this.executor_start_time_secs = new java.util.HashMap,java.lang.Long>(); this.worker_resources = new java.util.HashMap(); this.total_shared_off_heap = new java.util.HashMap(); this.owner = null; } @org.apache.storm.thrift.annotation.Nullable public java.lang.String get_master_code_dir() { return this.master_code_dir; } public void set_master_code_dir(@org.apache.storm.thrift.annotation.Nullable java.lang.String master_code_dir) { this.master_code_dir = master_code_dir; } public void unset_master_code_dir() { this.master_code_dir = null; } /** Returns true if field master_code_dir is set (has been assigned a value) and false otherwise */ public boolean is_set_master_code_dir() { return this.master_code_dir != null; } public void set_master_code_dir_isSet(boolean value) { if (!value) { this.master_code_dir = null; } } public int get_node_host_size() { return (this.node_host == null) ? 0 : this.node_host.size(); } public void put_to_node_host(java.lang.String key, java.lang.String val) { if (this.node_host == null) { this.node_host = new java.util.HashMap(); } this.node_host.put(key, val); } @org.apache.storm.thrift.annotation.Nullable public java.util.Map get_node_host() { return this.node_host; } public void set_node_host(@org.apache.storm.thrift.annotation.Nullable java.util.Map node_host) { this.node_host = node_host; } public void unset_node_host() { this.node_host = null; } /** Returns true if field node_host is set (has been assigned a value) and false otherwise */ public boolean is_set_node_host() { return this.node_host != null; } public void set_node_host_isSet(boolean value) { if (!value) { this.node_host = null; } } public int get_executor_node_port_size() { return (this.executor_node_port == null) ? 0 : this.executor_node_port.size(); } public void put_to_executor_node_port(java.util.List key, NodeInfo val) { if (this.executor_node_port == null) { this.executor_node_port = new java.util.HashMap,NodeInfo>(); } this.executor_node_port.put(key, val); } @org.apache.storm.thrift.annotation.Nullable public java.util.Map,NodeInfo> get_executor_node_port() { return this.executor_node_port; } public void set_executor_node_port(@org.apache.storm.thrift.annotation.Nullable java.util.Map,NodeInfo> executor_node_port) { this.executor_node_port = executor_node_port; } public void unset_executor_node_port() { this.executor_node_port = null; } /** Returns true if field executor_node_port is set (has been assigned a value) and false otherwise */ public boolean is_set_executor_node_port() { return this.executor_node_port != null; } public void set_executor_node_port_isSet(boolean value) { if (!value) { this.executor_node_port = null; } } public int get_executor_start_time_secs_size() { return (this.executor_start_time_secs == null) ? 0 : this.executor_start_time_secs.size(); } public void put_to_executor_start_time_secs(java.util.List key, long val) { if (this.executor_start_time_secs == null) { this.executor_start_time_secs = new java.util.HashMap,java.lang.Long>(); } this.executor_start_time_secs.put(key, val); } @org.apache.storm.thrift.annotation.Nullable public java.util.Map,java.lang.Long> get_executor_start_time_secs() { return this.executor_start_time_secs; } public void set_executor_start_time_secs(@org.apache.storm.thrift.annotation.Nullable java.util.Map,java.lang.Long> executor_start_time_secs) { this.executor_start_time_secs = executor_start_time_secs; } public void unset_executor_start_time_secs() { this.executor_start_time_secs = null; } /** Returns true if field executor_start_time_secs is set (has been assigned a value) and false otherwise */ public boolean is_set_executor_start_time_secs() { return this.executor_start_time_secs != null; } public void set_executor_start_time_secs_isSet(boolean value) { if (!value) { this.executor_start_time_secs = null; } } public int get_worker_resources_size() { return (this.worker_resources == null) ? 0 : this.worker_resources.size(); } public void put_to_worker_resources(NodeInfo key, WorkerResources val) { if (this.worker_resources == null) { this.worker_resources = new java.util.HashMap(); } this.worker_resources.put(key, val); } @org.apache.storm.thrift.annotation.Nullable public java.util.Map get_worker_resources() { return this.worker_resources; } public void set_worker_resources(@org.apache.storm.thrift.annotation.Nullable java.util.Map worker_resources) { this.worker_resources = worker_resources; } public void unset_worker_resources() { this.worker_resources = null; } /** Returns true if field worker_resources is set (has been assigned a value) and false otherwise */ public boolean is_set_worker_resources() { return this.worker_resources != null; } public void set_worker_resources_isSet(boolean value) { if (!value) { this.worker_resources = null; } } public int get_total_shared_off_heap_size() { return (this.total_shared_off_heap == null) ? 0 : this.total_shared_off_heap.size(); } public void put_to_total_shared_off_heap(java.lang.String key, double val) { if (this.total_shared_off_heap == null) { this.total_shared_off_heap = new java.util.HashMap(); } this.total_shared_off_heap.put(key, val); } @org.apache.storm.thrift.annotation.Nullable public java.util.Map get_total_shared_off_heap() { return this.total_shared_off_heap; } public void set_total_shared_off_heap(@org.apache.storm.thrift.annotation.Nullable java.util.Map total_shared_off_heap) { this.total_shared_off_heap = total_shared_off_heap; } public void unset_total_shared_off_heap() { this.total_shared_off_heap = null; } /** Returns true if field total_shared_off_heap is set (has been assigned a value) and false otherwise */ public boolean is_set_total_shared_off_heap() { return this.total_shared_off_heap != null; } public void set_total_shared_off_heap_isSet(boolean value) { if (!value) { this.total_shared_off_heap = null; } } @org.apache.storm.thrift.annotation.Nullable public java.lang.String get_owner() { return this.owner; } public void set_owner(@org.apache.storm.thrift.annotation.Nullable java.lang.String owner) { this.owner = owner; } public void unset_owner() { this.owner = null; } /** Returns true if field owner is set (has been assigned a value) and false otherwise */ public boolean is_set_owner() { return this.owner != null; } public void set_owner_isSet(boolean value) { if (!value) { this.owner = null; } } public void setFieldValue(_Fields field, @org.apache.storm.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case MASTER_CODE_DIR: if (value == null) { unset_master_code_dir(); } else { set_master_code_dir((java.lang.String)value); } break; case NODE_HOST: if (value == null) { unset_node_host(); } else { set_node_host((java.util.Map)value); } break; case EXECUTOR_NODE_PORT: if (value == null) { unset_executor_node_port(); } else { set_executor_node_port((java.util.Map,NodeInfo>)value); } break; case EXECUTOR_START_TIME_SECS: if (value == null) { unset_executor_start_time_secs(); } else { set_executor_start_time_secs((java.util.Map,java.lang.Long>)value); } break; case WORKER_RESOURCES: if (value == null) { unset_worker_resources(); } else { set_worker_resources((java.util.Map)value); } break; case TOTAL_SHARED_OFF_HEAP: if (value == null) { unset_total_shared_off_heap(); } else { set_total_shared_off_heap((java.util.Map)value); } break; case OWNER: if (value == null) { unset_owner(); } else { set_owner((java.lang.String)value); } break; } } @org.apache.storm.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case MASTER_CODE_DIR: return get_master_code_dir(); case NODE_HOST: return get_node_host(); case EXECUTOR_NODE_PORT: return get_executor_node_port(); case EXECUTOR_START_TIME_SECS: return get_executor_start_time_secs(); case WORKER_RESOURCES: return get_worker_resources(); case TOTAL_SHARED_OFF_HEAP: return get_total_shared_off_heap(); case OWNER: return get_owner(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case MASTER_CODE_DIR: return is_set_master_code_dir(); case NODE_HOST: return is_set_node_host(); case EXECUTOR_NODE_PORT: return is_set_executor_node_port(); case EXECUTOR_START_TIME_SECS: return is_set_executor_start_time_secs(); case WORKER_RESOURCES: return is_set_worker_resources(); case TOTAL_SHARED_OFF_HEAP: return is_set_total_shared_off_heap(); case OWNER: return is_set_owner(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that == null) return false; if (that instanceof Assignment) return this.equals((Assignment)that); return false; } public boolean equals(Assignment that) { if (that == null) return false; if (this == that) return true; boolean this_present_master_code_dir = true && this.is_set_master_code_dir(); boolean that_present_master_code_dir = true && that.is_set_master_code_dir(); if (this_present_master_code_dir || that_present_master_code_dir) { if (!(this_present_master_code_dir && that_present_master_code_dir)) return false; if (!this.master_code_dir.equals(that.master_code_dir)) return false; } boolean this_present_node_host = true && this.is_set_node_host(); boolean that_present_node_host = true && that.is_set_node_host(); if (this_present_node_host || that_present_node_host) { if (!(this_present_node_host && that_present_node_host)) return false; if (!this.node_host.equals(that.node_host)) return false; } boolean this_present_executor_node_port = true && this.is_set_executor_node_port(); boolean that_present_executor_node_port = true && that.is_set_executor_node_port(); if (this_present_executor_node_port || that_present_executor_node_port) { if (!(this_present_executor_node_port && that_present_executor_node_port)) return false; if (!this.executor_node_port.equals(that.executor_node_port)) return false; } boolean this_present_executor_start_time_secs = true && this.is_set_executor_start_time_secs(); boolean that_present_executor_start_time_secs = true && that.is_set_executor_start_time_secs(); if (this_present_executor_start_time_secs || that_present_executor_start_time_secs) { if (!(this_present_executor_start_time_secs && that_present_executor_start_time_secs)) return false; if (!this.executor_start_time_secs.equals(that.executor_start_time_secs)) return false; } boolean this_present_worker_resources = true && this.is_set_worker_resources(); boolean that_present_worker_resources = true && that.is_set_worker_resources(); if (this_present_worker_resources || that_present_worker_resources) { if (!(this_present_worker_resources && that_present_worker_resources)) return false; if (!this.worker_resources.equals(that.worker_resources)) return false; } boolean this_present_total_shared_off_heap = true && this.is_set_total_shared_off_heap(); boolean that_present_total_shared_off_heap = true && that.is_set_total_shared_off_heap(); if (this_present_total_shared_off_heap || that_present_total_shared_off_heap) { if (!(this_present_total_shared_off_heap && that_present_total_shared_off_heap)) return false; if (!this.total_shared_off_heap.equals(that.total_shared_off_heap)) return false; } boolean this_present_owner = true && this.is_set_owner(); boolean that_present_owner = true && that.is_set_owner(); if (this_present_owner || that_present_owner) { if (!(this_present_owner && that_present_owner)) return false; if (!this.owner.equals(that.owner)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((is_set_master_code_dir()) ? 131071 : 524287); if (is_set_master_code_dir()) hashCode = hashCode * 8191 + master_code_dir.hashCode(); hashCode = hashCode * 8191 + ((is_set_node_host()) ? 131071 : 524287); if (is_set_node_host()) hashCode = hashCode * 8191 + node_host.hashCode(); hashCode = hashCode * 8191 + ((is_set_executor_node_port()) ? 131071 : 524287); if (is_set_executor_node_port()) hashCode = hashCode * 8191 + executor_node_port.hashCode(); hashCode = hashCode * 8191 + ((is_set_executor_start_time_secs()) ? 131071 : 524287); if (is_set_executor_start_time_secs()) hashCode = hashCode * 8191 + executor_start_time_secs.hashCode(); hashCode = hashCode * 8191 + ((is_set_worker_resources()) ? 131071 : 524287); if (is_set_worker_resources()) hashCode = hashCode * 8191 + worker_resources.hashCode(); hashCode = hashCode * 8191 + ((is_set_total_shared_off_heap()) ? 131071 : 524287); if (is_set_total_shared_off_heap()) hashCode = hashCode * 8191 + total_shared_off_heap.hashCode(); hashCode = hashCode * 8191 + ((is_set_owner()) ? 131071 : 524287); if (is_set_owner()) hashCode = hashCode * 8191 + owner.hashCode(); return hashCode; } @Override public int compareTo(Assignment other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.valueOf(is_set_master_code_dir()).compareTo(other.is_set_master_code_dir()); if (lastComparison != 0) { return lastComparison; } if (is_set_master_code_dir()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.master_code_dir, other.master_code_dir); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_node_host()).compareTo(other.is_set_node_host()); if (lastComparison != 0) { return lastComparison; } if (is_set_node_host()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.node_host, other.node_host); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_executor_node_port()).compareTo(other.is_set_executor_node_port()); if (lastComparison != 0) { return lastComparison; } if (is_set_executor_node_port()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.executor_node_port, other.executor_node_port); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_executor_start_time_secs()).compareTo(other.is_set_executor_start_time_secs()); if (lastComparison != 0) { return lastComparison; } if (is_set_executor_start_time_secs()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.executor_start_time_secs, other.executor_start_time_secs); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_worker_resources()).compareTo(other.is_set_worker_resources()); if (lastComparison != 0) { return lastComparison; } if (is_set_worker_resources()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.worker_resources, other.worker_resources); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_total_shared_off_heap()).compareTo(other.is_set_total_shared_off_heap()); if (lastComparison != 0) { return lastComparison; } if (is_set_total_shared_off_heap()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.total_shared_off_heap, other.total_shared_off_heap); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.valueOf(is_set_owner()).compareTo(other.is_set_owner()); if (lastComparison != 0) { return lastComparison; } if (is_set_owner()) { lastComparison = org.apache.storm.thrift.TBaseHelper.compareTo(this.owner, other.owner); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.storm.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.storm.thrift.protocol.TProtocol iprot) throws org.apache.storm.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.storm.thrift.protocol.TProtocol oprot) throws org.apache.storm.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("Assignment("); boolean first = true; sb.append("master_code_dir:"); if (this.master_code_dir == null) { sb.append("null"); } else { sb.append(this.master_code_dir); } first = false; if (is_set_node_host()) { if (!first) sb.append(", "); sb.append("node_host:"); if (this.node_host == null) { sb.append("null"); } else { sb.append(this.node_host); } first = false; } if (is_set_executor_node_port()) { if (!first) sb.append(", "); sb.append("executor_node_port:"); if (this.executor_node_port == null) { sb.append("null"); } else { sb.append(this.executor_node_port); } first = false; } if (is_set_executor_start_time_secs()) { if (!first) sb.append(", "); sb.append("executor_start_time_secs:"); if (this.executor_start_time_secs == null) { sb.append("null"); } else { sb.append(this.executor_start_time_secs); } first = false; } if (is_set_worker_resources()) { if (!first) sb.append(", "); sb.append("worker_resources:"); if (this.worker_resources == null) { sb.append("null"); } else { sb.append(this.worker_resources); } first = false; } if (is_set_total_shared_off_heap()) { if (!first) sb.append(", "); sb.append("total_shared_off_heap:"); if (this.total_shared_off_heap == null) { sb.append("null"); } else { sb.append(this.total_shared_off_heap); } first = false; } if (is_set_owner()) { if (!first) sb.append(", "); sb.append("owner:"); if (this.owner == null) { sb.append("null"); } else { sb.append(this.owner); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.storm.thrift.TException { // check for required fields if (!is_set_master_code_dir()) { throw new org.apache.storm.thrift.protocol.TProtocolException("Required field 'master_code_dir' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.storm.thrift.protocol.TCompactProtocol(new org.apache.storm.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.storm.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.storm.thrift.protocol.TCompactProtocol(new org.apache.storm.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.storm.thrift.TException te) { throw new java.io.IOException(te); } } private static class AssignmentStandardSchemeFactory implements org.apache.storm.thrift.scheme.SchemeFactory { public AssignmentStandardScheme getScheme() { return new AssignmentStandardScheme(); } } private static class AssignmentStandardScheme extends org.apache.storm.thrift.scheme.StandardScheme { public void read(org.apache.storm.thrift.protocol.TProtocol iprot, Assignment struct) throws org.apache.storm.thrift.TException { org.apache.storm.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.storm.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // MASTER_CODE_DIR if (schemeField.type == org.apache.storm.thrift.protocol.TType.STRING) { struct.master_code_dir = iprot.readString(); struct.set_master_code_dir_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // NODE_HOST if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) { { org.apache.storm.thrift.protocol.TMap _map686 = iprot.readMapBegin(); struct.node_host = new java.util.HashMap(2*_map686.size); @org.apache.storm.thrift.annotation.Nullable java.lang.String _key687; @org.apache.storm.thrift.annotation.Nullable java.lang.String _val688; for (int _i689 = 0; _i689 < _map686.size; ++_i689) { _key687 = iprot.readString(); _val688 = iprot.readString(); struct.node_host.put(_key687, _val688); } iprot.readMapEnd(); } struct.set_node_host_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // EXECUTOR_NODE_PORT if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) { { org.apache.storm.thrift.protocol.TMap _map690 = iprot.readMapBegin(); struct.executor_node_port = new java.util.HashMap,NodeInfo>(2*_map690.size); @org.apache.storm.thrift.annotation.Nullable java.util.List _key691; @org.apache.storm.thrift.annotation.Nullable NodeInfo _val692; for (int _i693 = 0; _i693 < _map690.size; ++_i693) { { org.apache.storm.thrift.protocol.TList _list694 = iprot.readListBegin(); _key691 = new java.util.ArrayList(_list694.size); long _elem695; for (int _i696 = 0; _i696 < _list694.size; ++_i696) { _elem695 = iprot.readI64(); _key691.add(_elem695); } iprot.readListEnd(); } _val692 = new NodeInfo(); _val692.read(iprot); struct.executor_node_port.put(_key691, _val692); } iprot.readMapEnd(); } struct.set_executor_node_port_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // EXECUTOR_START_TIME_SECS if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) { { org.apache.storm.thrift.protocol.TMap _map697 = iprot.readMapBegin(); struct.executor_start_time_secs = new java.util.HashMap,java.lang.Long>(2*_map697.size); @org.apache.storm.thrift.annotation.Nullable java.util.List _key698; long _val699; for (int _i700 = 0; _i700 < _map697.size; ++_i700) { { org.apache.storm.thrift.protocol.TList _list701 = iprot.readListBegin(); _key698 = new java.util.ArrayList(_list701.size); long _elem702; for (int _i703 = 0; _i703 < _list701.size; ++_i703) { _elem702 = iprot.readI64(); _key698.add(_elem702); } iprot.readListEnd(); } _val699 = iprot.readI64(); struct.executor_start_time_secs.put(_key698, _val699); } iprot.readMapEnd(); } struct.set_executor_start_time_secs_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // WORKER_RESOURCES if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) { { org.apache.storm.thrift.protocol.TMap _map704 = iprot.readMapBegin(); struct.worker_resources = new java.util.HashMap(2*_map704.size); @org.apache.storm.thrift.annotation.Nullable NodeInfo _key705; @org.apache.storm.thrift.annotation.Nullable WorkerResources _val706; for (int _i707 = 0; _i707 < _map704.size; ++_i707) { _key705 = new NodeInfo(); _key705.read(iprot); _val706 = new WorkerResources(); _val706.read(iprot); struct.worker_resources.put(_key705, _val706); } iprot.readMapEnd(); } struct.set_worker_resources_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // TOTAL_SHARED_OFF_HEAP if (schemeField.type == org.apache.storm.thrift.protocol.TType.MAP) { { org.apache.storm.thrift.protocol.TMap _map708 = iprot.readMapBegin(); struct.total_shared_off_heap = new java.util.HashMap(2*_map708.size); @org.apache.storm.thrift.annotation.Nullable java.lang.String _key709; double _val710; for (int _i711 = 0; _i711 < _map708.size; ++_i711) { _key709 = iprot.readString(); _val710 = iprot.readDouble(); struct.total_shared_off_heap.put(_key709, _val710); } iprot.readMapEnd(); } struct.set_total_shared_off_heap_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // OWNER if (schemeField.type == org.apache.storm.thrift.protocol.TType.STRING) { struct.owner = iprot.readString(); struct.set_owner_isSet(true); } else { org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.storm.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.storm.thrift.protocol.TProtocol oprot, Assignment struct) throws org.apache.storm.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.master_code_dir != null) { oprot.writeFieldBegin(MASTER_CODE_DIR_FIELD_DESC); oprot.writeString(struct.master_code_dir); oprot.writeFieldEnd(); } if (struct.node_host != null) { if (struct.is_set_node_host()) { oprot.writeFieldBegin(NODE_HOST_FIELD_DESC); { oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.STRING, struct.node_host.size())); for (java.util.Map.Entry _iter712 : struct.node_host.entrySet()) { oprot.writeString(_iter712.getKey()); oprot.writeString(_iter712.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.executor_node_port != null) { if (struct.is_set_executor_node_port()) { oprot.writeFieldBegin(EXECUTOR_NODE_PORT_FIELD_DESC); { oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.LIST, org.apache.storm.thrift.protocol.TType.STRUCT, struct.executor_node_port.size())); for (java.util.Map.Entry, NodeInfo> _iter713 : struct.executor_node_port.entrySet()) { { oprot.writeListBegin(new org.apache.storm.thrift.protocol.TList(org.apache.storm.thrift.protocol.TType.I64, _iter713.getKey().size())); for (long _iter714 : _iter713.getKey()) { oprot.writeI64(_iter714); } oprot.writeListEnd(); } _iter713.getValue().write(oprot); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.executor_start_time_secs != null) { if (struct.is_set_executor_start_time_secs()) { oprot.writeFieldBegin(EXECUTOR_START_TIME_SECS_FIELD_DESC); { oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.LIST, org.apache.storm.thrift.protocol.TType.I64, struct.executor_start_time_secs.size())); for (java.util.Map.Entry, java.lang.Long> _iter715 : struct.executor_start_time_secs.entrySet()) { { oprot.writeListBegin(new org.apache.storm.thrift.protocol.TList(org.apache.storm.thrift.protocol.TType.I64, _iter715.getKey().size())); for (long _iter716 : _iter715.getKey()) { oprot.writeI64(_iter716); } oprot.writeListEnd(); } oprot.writeI64(_iter715.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.worker_resources != null) { if (struct.is_set_worker_resources()) { oprot.writeFieldBegin(WORKER_RESOURCES_FIELD_DESC); { oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRUCT, org.apache.storm.thrift.protocol.TType.STRUCT, struct.worker_resources.size())); for (java.util.Map.Entry _iter717 : struct.worker_resources.entrySet()) { _iter717.getKey().write(oprot); _iter717.getValue().write(oprot); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.total_shared_off_heap != null) { if (struct.is_set_total_shared_off_heap()) { oprot.writeFieldBegin(TOTAL_SHARED_OFF_HEAP_FIELD_DESC); { oprot.writeMapBegin(new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.DOUBLE, struct.total_shared_off_heap.size())); for (java.util.Map.Entry _iter718 : struct.total_shared_off_heap.entrySet()) { oprot.writeString(_iter718.getKey()); oprot.writeDouble(_iter718.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } } if (struct.owner != null) { if (struct.is_set_owner()) { oprot.writeFieldBegin(OWNER_FIELD_DESC); oprot.writeString(struct.owner); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class AssignmentTupleSchemeFactory implements org.apache.storm.thrift.scheme.SchemeFactory { public AssignmentTupleScheme getScheme() { return new AssignmentTupleScheme(); } } private static class AssignmentTupleScheme extends org.apache.storm.thrift.scheme.TupleScheme { @Override public void write(org.apache.storm.thrift.protocol.TProtocol prot, Assignment struct) throws org.apache.storm.thrift.TException { org.apache.storm.thrift.protocol.TTupleProtocol oprot = (org.apache.storm.thrift.protocol.TTupleProtocol) prot; oprot.writeString(struct.master_code_dir); java.util.BitSet optionals = new java.util.BitSet(); if (struct.is_set_node_host()) { optionals.set(0); } if (struct.is_set_executor_node_port()) { optionals.set(1); } if (struct.is_set_executor_start_time_secs()) { optionals.set(2); } if (struct.is_set_worker_resources()) { optionals.set(3); } if (struct.is_set_total_shared_off_heap()) { optionals.set(4); } if (struct.is_set_owner()) { optionals.set(5); } oprot.writeBitSet(optionals, 6); if (struct.is_set_node_host()) { { oprot.writeI32(struct.node_host.size()); for (java.util.Map.Entry _iter719 : struct.node_host.entrySet()) { oprot.writeString(_iter719.getKey()); oprot.writeString(_iter719.getValue()); } } } if (struct.is_set_executor_node_port()) { { oprot.writeI32(struct.executor_node_port.size()); for (java.util.Map.Entry, NodeInfo> _iter720 : struct.executor_node_port.entrySet()) { { oprot.writeI32(_iter720.getKey().size()); for (long _iter721 : _iter720.getKey()) { oprot.writeI64(_iter721); } } _iter720.getValue().write(oprot); } } } if (struct.is_set_executor_start_time_secs()) { { oprot.writeI32(struct.executor_start_time_secs.size()); for (java.util.Map.Entry, java.lang.Long> _iter722 : struct.executor_start_time_secs.entrySet()) { { oprot.writeI32(_iter722.getKey().size()); for (long _iter723 : _iter722.getKey()) { oprot.writeI64(_iter723); } } oprot.writeI64(_iter722.getValue()); } } } if (struct.is_set_worker_resources()) { { oprot.writeI32(struct.worker_resources.size()); for (java.util.Map.Entry _iter724 : struct.worker_resources.entrySet()) { _iter724.getKey().write(oprot); _iter724.getValue().write(oprot); } } } if (struct.is_set_total_shared_off_heap()) { { oprot.writeI32(struct.total_shared_off_heap.size()); for (java.util.Map.Entry _iter725 : struct.total_shared_off_heap.entrySet()) { oprot.writeString(_iter725.getKey()); oprot.writeDouble(_iter725.getValue()); } } } if (struct.is_set_owner()) { oprot.writeString(struct.owner); } } @Override public void read(org.apache.storm.thrift.protocol.TProtocol prot, Assignment struct) throws org.apache.storm.thrift.TException { org.apache.storm.thrift.protocol.TTupleProtocol iprot = (org.apache.storm.thrift.protocol.TTupleProtocol) prot; struct.master_code_dir = iprot.readString(); struct.set_master_code_dir_isSet(true); java.util.BitSet incoming = iprot.readBitSet(6); if (incoming.get(0)) { { org.apache.storm.thrift.protocol.TMap _map726 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.STRING, iprot.readI32()); struct.node_host = new java.util.HashMap(2*_map726.size); @org.apache.storm.thrift.annotation.Nullable java.lang.String _key727; @org.apache.storm.thrift.annotation.Nullable java.lang.String _val728; for (int _i729 = 0; _i729 < _map726.size; ++_i729) { _key727 = iprot.readString(); _val728 = iprot.readString(); struct.node_host.put(_key727, _val728); } } struct.set_node_host_isSet(true); } if (incoming.get(1)) { { org.apache.storm.thrift.protocol.TMap _map730 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.LIST, org.apache.storm.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.executor_node_port = new java.util.HashMap,NodeInfo>(2*_map730.size); @org.apache.storm.thrift.annotation.Nullable java.util.List _key731; @org.apache.storm.thrift.annotation.Nullable NodeInfo _val732; for (int _i733 = 0; _i733 < _map730.size; ++_i733) { { org.apache.storm.thrift.protocol.TList _list734 = new org.apache.storm.thrift.protocol.TList(org.apache.storm.thrift.protocol.TType.I64, iprot.readI32()); _key731 = new java.util.ArrayList(_list734.size); long _elem735; for (int _i736 = 0; _i736 < _list734.size; ++_i736) { _elem735 = iprot.readI64(); _key731.add(_elem735); } } _val732 = new NodeInfo(); _val732.read(iprot); struct.executor_node_port.put(_key731, _val732); } } struct.set_executor_node_port_isSet(true); } if (incoming.get(2)) { { org.apache.storm.thrift.protocol.TMap _map737 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.LIST, org.apache.storm.thrift.protocol.TType.I64, iprot.readI32()); struct.executor_start_time_secs = new java.util.HashMap,java.lang.Long>(2*_map737.size); @org.apache.storm.thrift.annotation.Nullable java.util.List _key738; long _val739; for (int _i740 = 0; _i740 < _map737.size; ++_i740) { { org.apache.storm.thrift.protocol.TList _list741 = new org.apache.storm.thrift.protocol.TList(org.apache.storm.thrift.protocol.TType.I64, iprot.readI32()); _key738 = new java.util.ArrayList(_list741.size); long _elem742; for (int _i743 = 0; _i743 < _list741.size; ++_i743) { _elem742 = iprot.readI64(); _key738.add(_elem742); } } _val739 = iprot.readI64(); struct.executor_start_time_secs.put(_key738, _val739); } } struct.set_executor_start_time_secs_isSet(true); } if (incoming.get(3)) { { org.apache.storm.thrift.protocol.TMap _map744 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRUCT, org.apache.storm.thrift.protocol.TType.STRUCT, iprot.readI32()); struct.worker_resources = new java.util.HashMap(2*_map744.size); @org.apache.storm.thrift.annotation.Nullable NodeInfo _key745; @org.apache.storm.thrift.annotation.Nullable WorkerResources _val746; for (int _i747 = 0; _i747 < _map744.size; ++_i747) { _key745 = new NodeInfo(); _key745.read(iprot); _val746 = new WorkerResources(); _val746.read(iprot); struct.worker_resources.put(_key745, _val746); } } struct.set_worker_resources_isSet(true); } if (incoming.get(4)) { { org.apache.storm.thrift.protocol.TMap _map748 = new org.apache.storm.thrift.protocol.TMap(org.apache.storm.thrift.protocol.TType.STRING, org.apache.storm.thrift.protocol.TType.DOUBLE, iprot.readI32()); struct.total_shared_off_heap = new java.util.HashMap(2*_map748.size); @org.apache.storm.thrift.annotation.Nullable java.lang.String _key749; double _val750; for (int _i751 = 0; _i751 < _map748.size; ++_i751) { _key749 = iprot.readString(); _val750 = iprot.readDouble(); struct.total_shared_off_heap.put(_key749, _val750); } } struct.set_total_shared_off_heap_isSet(true); } if (incoming.get(5)) { struct.owner = iprot.readString(); struct.set_owner_isSet(true); } } } private static S scheme(org.apache.storm.thrift.protocol.TProtocol proto) { return (org.apache.storm.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } } |
blob | blob, long method | t | t | t | long method | 0 | 15015 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/Assignment.java/#L26-L1404 | 1 | 5343 | 15015 | major | |
| 4708 | YES I found bad smells the bad smells are: 1. Commented-out code 2. Long method 3. Complex conditional logic 4. Feature envy 5. Use of System.out.println() instead of using a logger 6. Magic numbers 7. Lack of proper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Commented-out code2 Long method3 Complex conditional logic4 Feature envy5 Use of Systemoutprintln() instead of using a logger6 Magic numbers7 Lack of proper exception handling | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 2 | 4708 | 12628 | minor | ||
| 1288 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10614 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1288 | 10614 | minor | ||
| 1460 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Unclear variable names (e.g. "first", "last", "rows", "ses") 4. Poor formatting and indenting 5. Excessive commenting 6. Code duplication 7. Violation of single responsibility principle - the method is responsible for too many tasks 8. Lack of proper exception handling 9. Inefficient use of collections (e.g. using a list instead of a set) 10. Hard-coded values 11. Poor class design (e.g. too many dependencies and method calls) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy3 Unclear variable names (eg "first", "last", "rows", "ses")4 Poor formatting and indenting5 Excessive commenting6 Code duplication7 Violation of single responsibility principle - the method is responsible for too many tasks8 Lack of proper exception handling 9 Inefficient use of collections (eg using a list instead of a set) | t | f | t | "last", "rows", "ses")4. Poor formatting and indenting5. Excessive commenting6. Code duplication7. Violation of single responsibility principle - the method is responsible for too many tasks8. Lack of proper exception handling 9. Inefficient use of collections (e.g. using a list instead of a set) | 0 | 11021 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1460 | 11021 | minor | |
| 1925 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (repeated try-catch block) 4. Conditional complexity (multiple if/else statements) 5. Inconsistent naming conventions (some variables use camel case, others use underscores) 6. Poor exception handling (all exceptions are caught and logged, but no further action is taken) 7. Magic numbers used for calculations (e.g. division by 100f) 8. Nested conditionals (if/else within another if/else) 9. Inefficient use of memory (converting integers to floats for calculations) 10. Comments indicating potential issues that need to be fixed (indicates unmaintainable code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy3 Duplicate code (repeated try-catch block)4 Conditional complexity (multiple if/else statements)5 Inconsistent naming conventions (some variables use camel case, others use underscores)6 Poor exception handling (all exceptions are caught and logged, but no further action is taken)7 Magic numbers used for calculations (eg division by | t | f | t | others use underscores)6. Poor exception handling (all exceptions are caught and logged, but no further action is taken)7. Magic numbers used for calculations (e.g. division by | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1925 | 12434 | critical | |
| 1687 | YES, I found bad smells: the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (specifically, the try/catch blocks for loading the comparator) 4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator) 5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException) 6. Use of multiple exit points (through the use of "throw" statements within the method) 7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes) 8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly) 9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) 10. Inadequate comments (lack of comments explaining the purpose and functionality of the code) 11. High cyclomatic complexity (multiple nested try/catch blocks and if statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long method 2 Feature envy3 Duplicate code (specifically, the try/catch blocks for loading the comparator)4 Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5 Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6 Use of multiple exit points (through the use of "throw" statements within the method)7 Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8 Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9 Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | t | f | t | the try/catch blocks for loading the comparator)4. Inconsistent naming conventions (classLoadComparator instead of loadClassComparator)5. Empty catch clauses (for ClassNotFoundException, InstantiationException, and IllegalAccessException)6. Use of multiple exit points (through the use of "throw" statements within the method)7. Mixed responsibilities (the method is both instantiating and loading a comparator, and also setting and injecting its attributes)8. Non-encapsulated logic (the method is accessing and manipulating attributes of the comparator directly)9. Inadequate error handling (only logging error messages and not providing any meaningful information to the caller) | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 1687 | 11691 | major | |
| 900 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 900 | 8153 | major | ||
| 4024 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10635 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 1 | 4024 | 10635 | critical | |
| 1695 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 11719 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 1 | 1695 | 11719 | minor | |
| 2645 | YES I found bad smells! the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers (".class") 4. Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt") 5. Lack of proper documentation/commenting 6. Nested if statements and loops 7. Inconsistent formatting and spacing 8. Potential resource leak (input and output streams are not properly handled) 9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) 10. Poor variable and method naming 11. Lack of error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Feature envy3 Magic numbers ("class")4 Use of abbreviations ("wd", "cr", "cw", "cv", "b", "os", "is", "f", "dt")5 Lack of proper documentation/commenting6 Nested if statements and loops7 Inconsistent formatting and spacing8 Potential resource leak (input and output streams are not properly handled)9 Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | t | f | t | "cr", "cw", "cv", "b", "os", "is", "f", "dt")5. Lack of proper documentation/commenting6. Nested if statements and loops7. Inconsistent formatting and spacing8. Potential resource leak (input and output streams are not properly handled)9. Multiple responsibilities (weaving classes, manipulating byte arrays, and handling file operations within one method) | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2645 | 15150 | major | |
| 2371 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | data class | t | t | t | 0 | 14308 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 1 | 2371 | 14308 | minor | ||
| 2156 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2156 | 13302 | major | ||
| 963 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method 2 Feature Envy | t | f | t | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 2 | 963 | 8574 | major | ||
| 1962 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12586 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1962 | 12586 | minor | ||
| 1957 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | blob, feature envy, long method | t | t | f | blob, feature envy | long method | 0 | 12568 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 1957 | 12568 | critical |
| 747 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | 1. long method | t | t | t | 0 | 7016 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 747 | 7016 | minor | ||
| 4154 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface IAopReferenceModel { void start(); void shutdown(); void removeProject(IJavaProject project); void addProject(IJavaProject project, IAopProject aopProject); void fireModelChanged(); List getAdviceDefinition(IJavaElement je); List getAllReferences(); List getAllReferencesForResource(IResource resource); IAopProject getProject(IJavaProject project); Collection getProjects(); boolean isAdvice(IJavaElement je); boolean isAdvised(IJavaElement je); boolean isAdvised(IBean bean); void registerAopModelChangedListener(IAopModelChangedListener listener); void unregisterAopModelChangedListener(IAopModelChangedListener listener); void clearProjects(); } |
blob | blob, long method | t | t | t | long method | 0 | 10943 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.aop.core/src/org/springframework/ide/eclipse/aop/core/model/IAopReferenceModel.java/#L24-L58 | 1 | 4154 | 10943 | minor | |
| 45 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final static class TypeList { Hashtable types; TypeList() { } TypeList(Vector typeNames) { types = new Hashtable(); for ( int i = 0; i < typeNames.size(); i++ ) { String t = ((String) typeNames.elementAt(i)).toLowerCase(); types.put(t, t); } } final boolean contains(String type) { if ( types == null ) { return true; //defaults to all } return types.containsKey(type); } } |
data class | data class | t | t | t | 0 | 833 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.traceformat/share/classes/com/ibm/jvm/format/Util.java/#L631-L655 | 1 | 45 | 833 | minor | ||
| 2646 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TemporaryFolderExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private TemporaryFolder temporaryFolder; @Override public void beforeEach(ExtensionContext context) throws Exception { temporaryFolder = new TemporaryFolder(Files.createTempDir()); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return (parameterContext.getParameter().getType() == TemporaryFolder.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return temporaryFolder; } @Override public void afterEach(ExtensionContext context) throws Exception { FileUtils.deleteDirectory(temporaryFolder.getTempDir()); } public TemporaryFolder getTemporaryFolder() { return temporaryFolder; } public static class TemporaryFolder { private final File tempDir; private final String folderPath; public TemporaryFolder(File tempDir) { this.tempDir = tempDir; this.folderPath = tempDir.getPath() + "/"; } public File getTempDir() { return tempDir; } public String getFolderPath() { return folderPath; } } } |
data class | data class, long method | t | t | t | long method | 0 | 15154 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/testing/src/main/java/org/apache/james/junit/TemporaryFolderExtension.java/#L34-L79 | 1 | 2646 | 15154 | minor | |
| 1985 | YES I found bad smells the bad smells are: 1. Duplicated code, 2. Feature envy, 3. Long method, 4. Lazy class, 5. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Duplicated code, 2 Feature envy, 3 Long method, 4 Lazy class, 5 Long parameter list | t | f | t | . Duplicated code, 2. Feature envy, 4. Lazy class, 5. Long parameter list | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 1985 | 12651 | major | |
| 2915 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | long method | t | t | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 1 | 2915 | 2253 | major | ||
| 550 | The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void uncompressed(Blackhole blackhole) { final ImmutableConciseSet set = ImmutableConciseSet.complement(null, emptyRows); blackhole.consume(set); assert (emptyRows == set.size()); } |
feature envy | Long method2 Feature envy | f | f | t | 0 | 5563 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/benchmarks/src/main/java/org/apache/druid/benchmark/ConciseComplementBenchmark.java/#L43-L51 | 2 | 550 | 5563 | minor | ||
| 420 | {"message":"YES I found bad smells","detected_bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PerforceScmProvider extends AbstractScmProvider { private static final String[] PROTOCOLS = { "tcp", "tcp4", "tcp6", "tcp46", "tcp64", "ssl", "ssl4", "ssl6", "ssl46", "ssl64" }; // ---------------------------------------------------------------------- // ScmProvider Implementation // ---------------------------------------------------------------------- public boolean requiresEditMode() { return true; } public ScmProviderRepository makeProviderScmRepository( String scmSpecificUrl, char delimiter ) throws ScmRepositoryException { String protocol = null; String path; int port = 0; String host = null; //minimal logic to support perforce protocols in scm url, and keep the next part unchange int i0 = scmSpecificUrl.indexOf( delimiter ); if ( i0 > 0 ) { protocol = scmSpecificUrl.substring( 0, i0 ); HashSet protocols = new HashSet( Arrays.asList( PROTOCOLS ) ); if ( protocols.contains( protocol ) ) { scmSpecificUrl = scmSpecificUrl.substring( i0 + 1 ); } else { protocol = null; } } int i1 = scmSpecificUrl.indexOf( delimiter ); int i2 = scmSpecificUrl.indexOf( delimiter, i1 + 1 ); if ( i1 > 0 ) { int lastDelimiter = scmSpecificUrl.lastIndexOf( delimiter ); path = scmSpecificUrl.substring( lastDelimiter + 1 ); host = scmSpecificUrl.substring( 0, i1 ); // If there is tree parts in the scm url, the second is the port if ( i2 >= 0 ) { try { String tmp = scmSpecificUrl.substring( i1 + 1, lastDelimiter ); port = Integer.parseInt( tmp ); } catch ( NumberFormatException ex ) { throw new ScmRepositoryException( "The port has to be a number." ); } } } else { path = scmSpecificUrl; } String user = null; String password = null; if ( host != null && host.indexOf( '@' ) > 1 ) { user = host.substring( 0, host.indexOf( '@' ) ); host = host.substring( host.indexOf( '@' ) + 1 ); } if ( path.indexOf( '@' ) > 1 ) { if ( host != null ) { if ( getLogger().isWarnEnabled() ) { getLogger().warn( "Username as part of path is deprecated, the new format is " + "scm:perforce:[username@]host:port:path_to_repository" ); } } user = path.substring( 0, path.indexOf( '@' ) ); path = path.substring( path.indexOf( '@' ) + 1 ); } return new PerforceScmProviderRepository( protocol, host, port, path, user, password ); } public String getScmType() { return "perforce"; } /** {@inheritDoc} */ protected ChangeLogScmResult changelog( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters ) throws ScmException { PerforceChangeLogCommand command = new PerforceChangeLogCommand(); command.setLogger( getLogger() ); return (ChangeLogScmResult) command.execute( repository, fileSet, parameters ); } public AddScmResult add( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceAddCommand command = new PerforceAddCommand(); command.setLogger( getLogger() ); return (AddScmResult) command.execute( repository, fileSet, params ); } protected RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceRemoveCommand command = new PerforceRemoveCommand(); command.setLogger( getLogger() ); return (RemoveScmResult) command.execute( repository, fileSet, params ); } protected CheckInScmResult checkin( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckInCommand command = new PerforceCheckInCommand(); command.setLogger( getLogger() ); return (CheckInScmResult) command.execute( repository, fileSet, params ); } protected CheckOutScmResult checkout( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceCheckOutCommand command = new PerforceCheckOutCommand(); command.setLogger( getLogger() ); return (CheckOutScmResult) command.execute( repository, fileSet, params ); } protected DiffScmResult diff( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceDiffCommand command = new PerforceDiffCommand(); command.setLogger( getLogger() ); return (DiffScmResult) command.execute( repository, fileSet, params ); } protected EditScmResult edit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceEditCommand command = new PerforceEditCommand(); command.setLogger( getLogger() ); return (EditScmResult) command.execute( repository, fileSet, params ); } protected LoginScmResult login( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceLoginCommand command = new PerforceLoginCommand(); command.setLogger( getLogger() ); return (LoginScmResult) command.execute( repository, fileSet, params ); } protected StatusScmResult status( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceStatusCommand command = new PerforceStatusCommand(); command.setLogger( getLogger() ); return (StatusScmResult) command.execute( repository, fileSet, params ); } protected TagScmResult tag( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceTagCommand command = new PerforceTagCommand(); command.setLogger( getLogger() ); return (TagScmResult) command.execute( repository, fileSet, params ); } protected UnEditScmResult unedit( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUnEditCommand command = new PerforceUnEditCommand(); command.setLogger( getLogger() ); return (UnEditScmResult) command.execute( repository, fileSet, params ); } protected UpdateScmResult update( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceUpdateCommand command = new PerforceUpdateCommand(); command.setLogger( getLogger() ); return (UpdateScmResult) command.execute( repository, fileSet, params ); } protected BlameScmResult blame( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters params ) throws ScmException { PerforceBlameCommand command = new PerforceBlameCommand(); command.setLogger( getLogger() ); return (BlameScmResult) command.execute( repository, fileSet, params ); } public static Commandline createP4Command( PerforceScmProviderRepository repo, File workingDir ) { Commandline command = new Commandline(); command.setExecutable( "p4" ); if ( workingDir != null ) { // SCM-209 command.createArg().setValue( "-d" ); command.createArg().setValue( workingDir.getAbsolutePath() ); } if ( repo.getHost() != null ) { command.createArg().setValue( "-p" ); String value = ""; if ( ! StringUtils.isBlank( repo.getProtocol() ) ) { value += repo.getProtocol() + ":"; } value += repo.getHost(); if ( repo.getPort() != 0 ) { value += ":" + Integer.toString( repo.getPort() ); } command.createArg().setValue( value ); } if ( StringUtils.isNotEmpty( repo.getUser() ) ) { command.createArg().setValue( "-u" ); command.createArg().setValue( repo.getUser() ); } if ( StringUtils.isNotEmpty( repo.getPassword() ) ) { command.createArg().setValue( "-P" ); command.createArg().setValue( repo.getPassword() ); } return command; } public static String clean( String string ) { if ( string.indexOf( " -P " ) == -1 ) { return string; } int idx = string.indexOf( " -P " ) + 4; int end = string.indexOf( ' ', idx ); return string.substring( 0, idx ) + StringUtils.repeat( "*", end - idx ) + string.substring( end ); } /** * Given a path like "//depot/foo/bar", returns the * proper path to include everything beneath it. * * //depot/foo/bar -> //depot/foo/bar/... * //depot/foo/bar/ -> //depot/foo/bar/... * //depot/foo/bar/... -> //depot/foo/bar/... * * @param repoPath * @return */ public static String getCanonicalRepoPath( String repoPath ) { if ( repoPath.endsWith( "/..." ) ) { return repoPath; } else if ( repoPath.endsWith( "/" ) ) { return repoPath + "..."; } else { return repoPath + "/..."; } } private static final String NEWLINE = "\r\n"; /* * Clientspec name can be overridden with the system property below. I don't * know of any way for this code to get access to maven's settings.xml so this * is the best I can do. * * Sample clientspec: Client: mperham-mikeperham-dt-maven Root: d:\temp\target Owner: mperham View: //depot/sandbox/mperham/tsa/tsa-domain/... //mperham-mikeperham-dt-maven/... Description: Created by maven-scm-provider-perforce */ public static String createClientspec( ScmLogger logger, PerforceScmProviderRepository repo, File workDir, String repoPath ) { String clientspecName = getClientspecName( logger, repo, workDir ); String userName = getUsername( logger, repo ); String rootDir; try { // SCM-184 rootDir = workDir.getCanonicalPath(); } catch ( IOException ex ) { //getLogger().error("Error getting canonical path for working directory: " + workDir, ex); rootDir = workDir.getAbsolutePath(); } StringBuilder buf = new StringBuilder(); buf.append( "Client: " ).append( clientspecName ).append( NEWLINE ); buf.append( "Root: " ).append( rootDir ).append( NEWLINE ); buf.append( "Owner: " ).append( userName ).append( NEWLINE ); buf.append( "View:" ).append( NEWLINE ); buf.append( "\t" ).append( PerforceScmProvider.getCanonicalRepoPath( repoPath ) ); buf.append( " //" ).append( clientspecName ).append( "/..." ).append( NEWLINE ); buf.append( "Description:" ).append( NEWLINE ); buf.append( "\t" ).append( "Created by maven-scm-provider-perforce" ).append( NEWLINE ); return buf.toString(); } public static final String DEFAULT_CLIENTSPEC_PROPERTY = "maven.scm.perforce.clientspec.name"; public static String getClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String def = generateDefaultClientspecName( logger, repo, workDir ); // until someone put clearProperty in DefaultContinuumScm.getScmRepository( Project , boolean ) String l = System.getProperty( DEFAULT_CLIENTSPEC_PROPERTY, def ); if ( l == null || "".equals( l.trim() ) ) { return def; } return l; } private static String generateDefaultClientspecName( ScmLogger logger, PerforceScmProviderRepository repo, File workDir ) { String username = getUsername( logger, repo ); String hostname; String path; try { hostname = InetAddress.getLocalHost().getHostName(); // [SCM-370][SCM-351] client specs cannot contain forward slashes, spaces and ~; "-" is okay path = workDir.getCanonicalPath().replaceAll( "[/ ~]", "-" ); } catch ( UnknownHostException e ) { // Should never happen throw new RuntimeException( e ); } catch ( IOException e ) { throw new RuntimeException( e ); } return username + "-" + hostname + "-MavenSCM-" + path; } private static String getUsername( ScmLogger logger, PerforceScmProviderRepository repo ) { String username = PerforceInfoCommand.getInfo( logger, repo ).getEntry( "User name" ); if ( username == null ) { // os user != perforce user username = repo.getUser(); if ( username == null ) { username = System.getProperty( "user.name", "nouser" ); } } return username; } /** * This is a "safe" method which handles cases where repo.getPath() is * not actually a valid Perforce depot location. This is a frequent error * due to branches and directory naming where dir name != artifactId. * * @param log the logging object to use * @param repo the Perforce repo * @param basedir the base directory we are operating in. If pom.xml exists in this directory, * this method will verify repo.getPath()/pom.xml == p4 where basedir/pom.xml * @return repo.getPath if it is determined to be accurate. The p4 where location otherwise. */ public static String getRepoPath( ScmLogger log, PerforceScmProviderRepository repo, File basedir ) { PerforceWhereCommand where = new PerforceWhereCommand( log, repo ); // Handle an edge case where we release:prepare'd a module with an invalid SCM location. // In this case, the release.properties will contain the invalid URL for checkout purposes // during release:perform. In this case, the basedir is not the module root so we detect that // and remove the trailing target/checkout directory. if ( basedir.toString().replace( '\\', '/' ).endsWith( "/target/checkout" ) ) { String dir = basedir.toString(); basedir = new File( dir.substring( 0, dir.length() - "/target/checkout".length() ) ); log.debug( "Fixing checkout URL: " + basedir ); } File pom = new File( basedir, "pom.xml" ); String loc = repo.getPath(); log.debug( "SCM path in pom: " + loc ); if ( pom.exists() ) { loc = where.getDepotLocation( pom ); if ( loc == null ) { loc = repo.getPath(); log.debug( "cannot find depot => using " + loc ); } else if ( loc.endsWith( "/pom.xml" ) ) { loc = loc.substring( 0, loc.length() - "/pom.xml".length() ); log.debug( "Actual POM location: " + loc ); if ( !repo.getPath().equals( loc ) ) { log.info( "The SCM location in your pom.xml (" + repo.getPath() + ") is not equal to the depot location (" + loc + "). This happens frequently with branches. " + "Ignoring the SCM location." ); } } } return loc; } private static Boolean live = null; public static boolean isLive() { if ( live == null ) { if ( !Boolean.getBoolean( "maven.scm.testing" ) ) { // We are not executing in the tests so we are live. live = Boolean.TRUE; } else { // During unit tests, we need to check the local system // to see if the user has Perforce installed. If not, we mark // the provider as "not live" (or dead, I suppose!) and skip // anything that requires an active server connection. try { Commandline command = new Commandline(); command.setExecutable( "p4" ); Process proc = command.execute(); BufferedReader br = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); @SuppressWarnings( "unused" ) String line; while ( ( line = br.readLine() ) != null ) { //System.out.println(line); } int rc = proc.exitValue(); live = ( rc == 0 ? Boolean.TRUE : Boolean.FALSE ); } catch ( Exception e ) { e.printStackTrace(); live = Boolean.FALSE; } } } return live.booleanValue(); } } |
data class | long method, data class | t | t | t | long method | 0 | 4240 | https://github.com/apache/maven-scm/blob/6f876b4dc33372a8527f09c23c6f698e04a771c6/maven-scm-providers/maven-scm-provider-perforce/src/main/java/org/apache/maven/scm/provider/perforce/PerforceScmProvider.java/#L77-L558 | 1 | 420 | 4240 | major | |
| 517 | "YES I found bad smells: Long method, Feature envy, Complex conditionals, Inconsistent name, Hardcoded numbers, "the bad smells are: 1. Long method 2. Feature envy 3. Complex conditionals 4. Inconsistent name 5. Hardcoded numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ResolvableType forType( @Nullable Type type, @Nullable TypeProvider typeProvider, @Nullable VariableResolver variableResolver) { if (type == null && typeProvider != null) { type = SerializableTypeWrapper.forTypeProvider(typeProvider); } if (type == null) { return NONE; } // For simple Class references, build the wrapper right away - // no expensive resolution necessary, so not worth caching... if (type instanceof Class) { return new ResolvableType(type, typeProvider, variableResolver, (ResolvableType) null); } // Purge empty entries on access since we don't have a clean-up thread or the like. cache.purgeUnreferencedEntries(); // Check the cache - we may have a ResolvableType which has been resolved before... ResolvableType resultType = new ResolvableType(type, typeProvider, variableResolver); ResolvableType cachedType = cache.get(resultType); if (cachedType == null) { cachedType = new ResolvableType(type, typeProvider, variableResolver, resultType.hash); cache.put(cachedType, cachedType); } resultType.resolved = cachedType.resolved; return resultType; } |
long method | Long method2 Feature envy3 Complex conditionals4 Inconsistent name5 Hardcoded numbers | t | f | t | 0 | 5350 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-core/src/main/java/org/springframework/core/ResolvableType.java/#L1394-L1422 | 2 | 517 | 5350 | minor | ||
| 1636 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long Method | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 1636 | 11525 | minor | ||
| 336 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 336 | 3447 | minor | ||
| 319 | {"response":"YES I found bad smells","bad smells":["Blob","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetAgent extends Agent { //---------------------navigational members----------------------------------- // All these request objects point to the same physical request object. ConnectionRequestInterface connectionRequest_; StatementRequestInterface statementRequest_; ResultSetRequestInterface resultSetRequest_; // All these reply objects point to the same physical reply object. ConnectionReply connectionReply_; private ConnectionReply packageReply_; StatementReply statementReply_; ResultSetReply resultSetReply_; //---------------------navigational cheat-links------------------------------- // Cheat-links are for convenience only, and are not part of the conceptual model. // Warning: // Cheat-links should only be defined for invariant state data. // That is, the state data is set by the constructor and never changes. // Alias for (NetConnection) super.connection NetConnection netConnection_; // Alias for (Request) super.*Request, all in one // In the case of the NET implementation, these all point to the same physical request object. private Request request_; NetConnectionRequest netConnectionRequest_; private NetPackageRequest netPackageRequest_; private NetStatementRequest netStatementRequest_; private NetResultSetRequest netResultSetRequest_; // Alias for (Reply) super.*Reply, all in one. // In the case of the NET implementation, these all point to the same physical reply object. private Reply reply_; NetConnectionReply netConnectionReply_; private NetPackageReply netPackageReply_; private NetStatementReply netStatementReply_; private NetResultSetReply netResultSetReply_; //-----------------------------state------------------------------------------ Socket socket_; private InputStream rawSocketInputStream_; private OutputStream rawSocketOutputStream_; String server_; int port_; private int clientSSLMode_; private EbcdicCcsidManager ebcdicCcsidManager_; private Utf8CcsidManager utf8CcsidManager_; private CcsidManager currentCcsidManager_; // TODO: Remove target? Keep just one CcsidManager? //public CcsidManager targetCcsidManager_; Typdef typdef_; Typdef targetTypdef_; Typdef originalTargetTypdef_; // added to support typdef overrides private int svrcod_; int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7; int targetSqlam_ = orignalTargetSqlam_; SqlException exceptionOpeningSocket_ = null; SqlException exceptionConvertingRdbnam = null; /** * Flag which indicates that a writeChain has been started and data sent to * the server. * If true, starting a new write chain will throw a DisconnectException. * It is cleared when the write chain is ended. */ private boolean writeChainIsDirty_ = false; //---------------------constructors/finalizer--------------------------------- // Only used for testing public NetAgent(NetConnection netConnection, LogWriter logWriter) throws SqlException { super(netConnection, logWriter); this.netConnection_ = netConnection; } NetAgent(NetConnection netConnection, LogWriter netLogWriter, int loginTimeout, String server, int port, int clientSSLMode) throws SqlException { super(netConnection, netLogWriter); server_ = server; port_ = port; netConnection_ = netConnection; clientSSLMode_ = clientSSLMode; if (server_ == null) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET), "serverName"); } try { socket_ = (Socket)AccessController.doPrivileged( new OpenSocketAction(server, port, clientSSLMode_)); } catch (PrivilegedActionException e) { throw new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER), e.getException(), e.getException().getClass().getName(), server, port, e.getException().getMessage()); } // Set TCP/IP Socket Properties try { if (exceptionOpeningSocket_ == null) { socket_.setTcpNoDelay(true); // disables nagles algorithm socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2 socket_.setSoTimeout(loginTimeout * 1000); } } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION), e, e.getMessage()); } try { if (exceptionOpeningSocket_ == null) { rawSocketOutputStream_ = socket_.getOutputStream(); rawSocketInputStream_ = socket_.getInputStream(); } } catch (IOException e) { try { socket_.close(); } catch (IOException doNothing) { } exceptionOpeningSocket_ = new DisconnectException(this, new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM), e, e.getMessage()); } ebcdicCcsidManager_ = new EbcdicCcsidManager(); utf8CcsidManager_ = new Utf8CcsidManager(); currentCcsidManager_ = ebcdicCcsidManager_; if (netConnection_.isXAConnection()) { NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_); netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_; netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, netConnection_.commBufferSize_); netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_; netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } else { netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_); netStatementReply_ = (NetStatementReply) netResultSetReply_; netPackageReply_ = (NetPackageReply) netStatementReply_; netConnectionReply_ = (NetConnectionReply) netPackageReply_; reply_ = (Reply) netConnectionReply_; resultSetReply_ = new ResultSetReply(this, netResultSetReply_, netStatementReply_, netConnectionReply_); statementReply_ = (StatementReply) resultSetReply_; packageReply_ = (ConnectionReply) statementReply_; connectionReply_ = (ConnectionReply) packageReply_; netResultSetRequest_ = new NetResultSetRequest(this, netConnection_.commBufferSize_); netStatementRequest_ = (NetStatementRequest) netResultSetRequest_; netPackageRequest_ = (NetPackageRequest) netStatementRequest_; netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_; request_ = (Request) netConnectionRequest_; resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_; statementRequest_ = (StatementRequestInterface) netStatementRequest_; connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_; } } protected void resetAgent_(LogWriter netLogWriter, //CcsidManager sourceCcsidManager, //CcsidManager targetCcsidManager, int loginTimeout, String server, int port) throws SqlException { exceptionConvertingRdbnam = null; // most properties will remain unchanged on connect reset. targetTypdef_ = originalTargetTypdef_; svrcod_ = 0; // Set TCP/IP Socket Properties try { socket_.setSoTimeout(loginTimeout * 1000); } catch (SocketException e) { try { socket_.close(); } catch (IOException doNothing) { } throw new SqlException(logWriter_, new ClientMessageId(SQLState.SOCKET_EXCEPTION), e, e.getMessage()); } } void setSvrcod(int svrcod) { if (svrcod > svrcod_) { svrcod_ = svrcod; } } void clearSvrcod() { svrcod_ = CodePoint.SVRCOD_INFO; } private int getSvrcod() { return svrcod_; } public void flush_() throws DisconnectException { sendRequest(); reply_.initialize(); } // Close socket and its streams. public void close_() throws SqlException { // can we just close the socket here, do we need to close streams individually SqlException accumulatedExceptions = null; if (rawSocketInputStream_ != null) { try { rawSocketInputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes accumulatedExceptions = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); } finally { rawSocketInputStream_ = null; } } if (rawSocketOutputStream_ != null) { try { rawSocketOutputStream_.close(); } catch (IOException e) { // note when {6} = 0 it indicates the socket was closed. // this should be ok since we are going to go an close the socket // immediately following this call. // changing {4} to e.getMessage() may require pub changes SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { rawSocketOutputStream_ = null; } } if (socket_ != null) { try { socket_.close(); } catch (IOException e) { // again {6} = 0, indicates the socket was closed. // maybe set {4} to e.getMessage(). // do this for now and but may need to modify or // add this to the message pubs. SqlException latestException = new SqlException(logWriter_, new ClientMessageId(SQLState.COMMUNICATION_ERROR), e, e.getMessage()); accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions); } finally { socket_ = null; } } if (accumulatedExceptions != null) { throw accumulatedExceptions; } } /** * Specifies the maximum blocking time that should be used when sending * and receiving messages. The timeout is implemented by using the the * underlying socket implementation's timeout support. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @param timeout The timeout value in seconds. A value of 0 corresponds to * infinite timeout. */ protected void setTimeout(int timeout) { try { // Sets a timeout on the socket socket_.setSoTimeout(timeout * 1000); // convert to milliseconds } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.setTimeout: ignoring exception: " + se); } } } /** * Returns the current timeout value that is set on the socket. * * Note that the support for timeout on sockets is dependent on the OS * implementation. For the same reason we ignore any exceptions thrown * by the call to the socket layer. * * @return The timeout value in seconds. A value of 0 corresponds to * that no timeout is specified on the socket. */ protected int getTimeout() { int timeout = 0; // 0 is default timeout for sockets // Read the timeout currently set on the socket try { timeout = socket_.getSoTimeout(); } catch (SocketException se) { // Silently ignore any exceptions from the socket layer if (SanityManager.DEBUG) { System.out.println("NetAgent.getTimeout: ignoring exception: " + se); } } // Convert from milliseconds to seconds (note that this truncates // the results towards zero but that should not be a problem). timeout = timeout / 1000; return timeout; } private void sendRequest() throws DisconnectException { try { request_.flush(rawSocketOutputStream_); } catch (IOException e) { throwCommunicationsFailure(e); } } public InputStream getInputStream() { return rawSocketInputStream_; } public CcsidManager getCurrentCcsidManager() { return currentCcsidManager_; } public OutputStream getOutputStream() { return rawSocketOutputStream_; } void setInputStream(InputStream inputStream) { rawSocketInputStream_ = inputStream; } void setOutputStream(OutputStream outputStream) { rawSocketOutputStream_ = outputStream; } void throwCommunicationsFailure(Throwable cause) throws DisconnectException { //DisconnectException //accumulateReadExceptionAndDisconnect // note when {6} = 0 it indicates the socket was closed. // need to still validate any token values against message publications. accumulateChainBreakingReadExceptionAndThrow( new DisconnectException(this, new ClientMessageId(SQLState.COMMUNICATION_ERROR), cause, cause.getMessage())); } // ----------------------- call-down methods --------------------------------- protected void markChainBreakingException_() { setSvrcod(CodePoint.SVRCOD_ERROR); } public void checkForChainBreakingException_() throws SqlException { int svrcod = getSvrcod(); clearSvrcod(); if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker { super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one. } } private void writeDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.writeDeferredReset(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } /** * Marks the agent's write chain as dirty. A write chain is dirty when data * from it has been sent to the server. A dirty write chain cannot be reset * and reused for another request until the remaining data has been sent to * the server and the write chain properly ended. * * Resetting a dirty chain will cause the new request to be appended to the * unfinished request already at the server, which will likely lead to * cryptic syntax errors. */ void markWriteChainAsDirty() { writeChainIsDirty_ = true; } private void verifyWriteChainIsClean() throws DisconnectException { if (writeChainIsDirty_) { throw new DisconnectException(this, new ClientMessageId(SQLState.NET_WRITE_CHAIN_IS_DIRTY)); } } public void beginWriteChainOutsideUOW() throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); } public void beginWriteChain(ClientStatement statement) throws SqlException { verifyWriteChainIsClean(); request_.initialize(); writeDeferredResetConnection(); super.beginWriteChain(statement); } protected void endWriteChain() {} private void readDeferredResetConnection() throws SqlException { if (!netConnection_.resetConnectionAtFirstSql_) { return; } try { netConnection_.readDeferredReset(); checkForExceptions(); } catch (SqlException sqle) { DisconnectException de = new DisconnectException(this, new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET)); de.setNextException(sqle); throw de; } } protected void beginReadChain(ClientStatement statement) throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChain(statement); } protected void beginReadChainOutsideUOW() throws SqlException { // Clear here as endWriteChain may not always be called writeChainIsDirty_ = false; readDeferredResetConnection(); super.beginReadChainOutsideUOW(); } /** * Switches the current CCSID manager to UTF-8 */ void switchToUtf8CcsidMgr() { currentCcsidManager_ = utf8CcsidManager_; } /** * Switches the current CCSID manager to EBCDIC */ void switchToEbcdicMgr() { currentCcsidManager_ = ebcdicCcsidManager_; } } |
blob | blob, long method | t | t | t | long method | 0 | 3272 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.client/org/apache/derby/client/net/NetAgent.java/#L43-L550 | 1 | 319 | 3272 | minor | |
| 1812 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12063 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 1812 | 12063 | minor | |
| 1278 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 1278 | 10592 | minor | ||
| 568 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5726 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 568 | 5726 | minor | |
| 1757 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Table(name = "clusters") @NamedQueries({ @NamedQuery(name = "clusterByName", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.clusterName=:clusterName"), @NamedQuery(name = "allClusters", query = "SELECT clusters " + "FROM ClusterEntity clusters"), @NamedQuery(name = "clusterByResourceId", query = "SELECT cluster " + "FROM ClusterEntity cluster " + "WHERE cluster.resource.id=:resourceId") }) @Entity @TableGenerator(name = "cluster_id_generator", table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_value" , pkColumnValue = "cluster_id_seq" , initialValue = 1 ) public class ClusterEntity { @Id @Column(name = "cluster_id", nullable = false, insertable = true, updatable = true) @GeneratedValue(strategy = GenerationType.TABLE, generator = "cluster_id_generator") private Long clusterId; @Basic @Column(name = "cluster_name", nullable = false, insertable = true, updatable = true, unique = true, length = 100) private String clusterName; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "provisioning_state", insertable = true, updatable = true) private State provisioningState = State.INIT; @Basic @Enumerated(value = EnumType.STRING) @Column(name = "security_type", nullable = false, insertable = true, updatable = true) private SecurityType securityType = SecurityType.NONE; @Basic @Column(name = "desired_cluster_state", insertable = true, updatable = true) private String desiredClusterState = ""; @Basic @Column(name = "cluster_info", insertable = true, updatable = true) private String clusterInfo = ""; /** * Unidirectional one-to-one association to {@link StackEntity} */ @OneToOne @JoinColumn(name = "desired_stack_id", unique = false, nullable = false, insertable = true, updatable = true) private StackEntity desiredStack; @OneToMany(mappedBy = "clusterEntity") private Collection clusterServiceEntities; @OneToOne(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private ClusterStateEntity clusterStateEntity; @ManyToMany(mappedBy = "clusterEntities") private Collection hostEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection configGroupEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.ALL) private Collection requestScheduleEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE) private Collection serviceConfigEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection alertDefinitionEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetEntities; @OneToMany(mappedBy = "clusterEntity", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Collection widgetLayoutEntities; @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false) }) private ResourceEntity resource; @Basic @Column(name = "upgrade_id", nullable = true, insertable = false, updatable = false) private Long upgradeId; /** * {@code null} when there is no upgrade/downgrade in progress. */ @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn( name = "upgrade_id", referencedColumnName = "upgrade_id", nullable = true, insertable = false, updatable = true) private UpgradeEntity upgradeEntity = null; public Long getClusterId() { return clusterId; } public void setClusterId(Long clusterId) { this.clusterId = clusterId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getDesiredClusterState() { return defaultString(desiredClusterState); } public void setDesiredClusterState(String desiredClusterState) { this.desiredClusterState = desiredClusterState; } public String getClusterInfo() { return defaultString(clusterInfo); } public void setClusterInfo(String clusterInfo) { this.clusterInfo = clusterInfo; } public StackEntity getDesiredStack() { return desiredStack; } public void setDesiredStack(StackEntity desiredStack) { this.desiredStack = desiredStack; } /** * Gets whether the cluster is still initializing or has finished with its * deployment requests. * * @return either {@link State#INIT} or {@link State#INSTALLED}, * never {@code null}. */ public State getProvisioningState(){ return provisioningState; } /** * Sets whether the cluster is still initializing or has finished with its * deployment requests. * * @param provisioningState either {@link State#INIT} or * {@link State#INSTALLED}, never {@code null}. */ public void setProvisioningState(State provisioningState){ this.provisioningState = provisioningState; } /** * Gets this ClusterEntity's security type. * * @return the current SecurityType */ public SecurityType getSecurityType() { return securityType; } /** * Set's this ClusterEntity's security type * * @param securityType the new SecurityType */ public void setSecurityType(SecurityType securityType) { this.securityType = securityType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterEntity that = (ClusterEntity) o; if (!clusterId.equals(that.clusterId)) { return false; } if (!clusterName.equals(that.clusterName)) { return false; } return true; } @Override public int hashCode() { int result = null == clusterId ? 0 : clusterId.hashCode(); result = 31 * result + clusterName.hashCode(); return result; } public Collection getClusterServiceEntities() { return clusterServiceEntities; } public void setClusterServiceEntities(Collection clusterServiceEntities) { this.clusterServiceEntities = clusterServiceEntities; } public ClusterStateEntity getClusterStateEntity() { return clusterStateEntity; } public void setClusterStateEntity(ClusterStateEntity clusterStateEntity) { this.clusterStateEntity = clusterStateEntity; } public Collection getHostEntities() { return hostEntities; } public void setHostEntities(Collection hostEntities) { this.hostEntities = hostEntities; } public Collection getClusterConfigEntities() { return configEntities; } public void setClusterConfigEntities(Collection entities) { configEntities = entities; } public Collection getConfigGroupEntities() { return configGroupEntities; } public void setConfigGroupEntities(Collection configGroupEntities) { this.configGroupEntities = configGroupEntities; } public Collection getRequestScheduleEntities() { return requestScheduleEntities; } public void setRequestScheduleEntities(Collection requestScheduleEntities) { this.requestScheduleEntities = requestScheduleEntities; } public Collection getServiceConfigEntities() { return serviceConfigEntities; } public void setServiceConfigEntities(Collection serviceConfigEntities) { this.serviceConfigEntities = serviceConfigEntities; } public Collection getAlertDefinitionEntities() { return alertDefinitionEntities; } /** * Get the admin resource entity. * * @return the resource entity */ public ResourceEntity getResource() { return resource; } /** * Set the admin resource entity. * * @param resource the resource entity */ public void setResource(ResourceEntity resource) { this.resource = resource; } public UpgradeEntity getUpgradeEntity() { return upgradeEntity; } public void setUpgradeEntity(UpgradeEntity upgradeEntity) { this.upgradeEntity = upgradeEntity; } } |
data class | 'Data Class' | t | t | t | {',D,a,t,a," ",C,l,a,s,s,'} | {',D,a,a," ",C,l,a,s,s,'} | 0 | 11877 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ClusterEntity.java/#L48-L350 | 1 | 1757 | 11877 | major |
| 1891 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1891 | 12314 | minor | ||
| 402 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | 1. long method | t | t | t | 0 | 4103 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 402 | 4103 | major | ||
| 2101 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13160 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 2 | 2101 | 13160 | minor | ||
| 2748 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | 1. long method | t | t | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2748 | 804 | major | ||
| 1854 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RSLSettings { /** * A RSL URL and a policy file URL. */ public static class RSLAndPolicyFileURLPair { /** * Create a new RSL URL and Policy File URL pair. * * @param rslURL THe URL of the runtime shared library. * @param policyFileURL The URL of the policy file. */ public RSLAndPolicyFileURLPair(String rslURL, String policyFileURL) { this.rslURL = rslURL; this.policyFileURL = policyFileURL; } private String rslURL; private String policyFileURL; /** * @return the url of the RSL to load. */ public String getRSLURL() { return rslURL; } /** * @return the url of the policy file. */ public String getPolicyFileURL() { return policyFileURL; } } /** * The extension given to a signed RLS that is assumed to be signed. * Unsigned RSLs should use the standard "swf" extension. */ private static final String SIGNED_RSL_URL_EXTENSION = "swz"; private static final String SIGNED_RSL_URL_DOT_EXTENSION = "." + SIGNED_RSL_URL_EXTENSION; /** * Test if the url is a signed RSL. Signed RSL have a .swz extension. * * @param url url to test, the file specified by the url does not * need to exist. * @return true if the url specifies a signed rsl, false otherwise. */ public static boolean isSignedRSL(String url) { if (url == null) return false; return url.endsWith(SIGNED_RSL_URL_DOT_EXTENSION); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ RSLSettings(IFileSpecification libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = new File(libraryFile.getPath()); rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } /** * Create RSLSettings with: * - a default {@link ApplicationDomainTarget} * - verify digest set to true * * @param libraryFile the library whose classes will be removed * from the application. May not be null. * @throws NullPointerException if libraryFile is null. */ public RSLSettings(File libraryFile) { if (libraryFile == null) throw new NullPointerException("libraryFile may not be null"); this.libraryFile = libraryFile; rslURLs = new ArrayList(); setApplicationDomain(ApplicationDomainTarget.DEFAULT); setVerifyDigest(true); } private File libraryFile; // the library whose definitions are externed private List rslURLs; // list of rsls and failovers private ApplicationDomainTarget applicationDomain; private boolean verifyDigest; // if true the digest will be verified at runtime private boolean forceLoad; // true if the RSL should be forced to load regardless of its use /** * @return true if the RSL should be force loaded, false otherwise. */ public boolean isForceLoad() { return forceLoad; } /** * Sets a flag on the RSL so the compiler is not allowed to remove it when * the "remove unused RSLs" feature is on. * * @param forceLoad true to force the RSL to be loaded at runtime, false otherwise. */ public void setForceLoad(boolean forceLoad) { this.forceLoad = forceLoad; } /** * @return a List of {@link RSLAndPolicyFileURLPair} */ public List getRSLURLs() { return rslURLs; } /** * Add a new RSL URL and Policy file URL. This first pair is the primary * RSL and the following RSLs are failover RSLs. * * @param rslURL A String representing the URL to load the RSL from. May * not be null. * @param policyFileURL A String representing the URL to load a policy file * from. This is optional and may be null to indicate there is no policy * file. * @throws NullPointerException if rslURL is null. */ public void addRSLURLAndPolicyFileURL(String rslURL, String policyFileURL) { if (rslURL == null) throw new NullPointerException("rslURL may not be null"); rslURLs.add(new RSLAndPolicyFileURLPair(rslURL, policyFileURL)); } /** * @return the libraryFile */ public File getLibraryFile() { return libraryFile; } /** * @param applicationDomain the new value of the applicationDomain. */ public void setApplicationDomain(ApplicationDomainTarget applicationDomain) { this.applicationDomain = applicationDomain; } /** * One of {@link ApplicationDomainTarget} that control which domain an RSL * is loaded into. * * @return the applicationDomain */ public ApplicationDomainTarget getApplicationDomain() { return applicationDomain; } /** * Change the value of the verify digests flag. * * @param verifyDigest The new value of the verify digests flag. */ public void setVerifyDigest(boolean verifyDigest) { this.verifyDigest = verifyDigest; } /** * @return if true, the RSL's digest must be verified at runtime. */ public boolean getVerifyDigest() { return verifyDigest; } } |
data class | long method, data class | t | t | t | long method | 0 | 12206 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/config/RSLSettings.java/#L34-L233 | 1 | 1854 | 12206 | minor | |
| 1292 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | data class, blob | t | t | t | blob | 0 | 10621 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 1 | 1292 | 10621 | major | |
| 1174 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | data class | t | t | t | 0 | 10210 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 1174 | 10210 | critical | ||
| 1058 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method | t | t | t | 0 | 9520 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1058 | 9520 | major | ||
| 1325 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 2 | 1325 | 10702 | minor | ||
| 1730 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractDeadLetterStrategy implements DeadLetterStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractDeadLetterStrategy.class); private boolean processNonPersistent = false; private boolean processExpired = true; private boolean enableAudit = true; private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit(); private long expiration; @Override public void rollback(Message message) { if (message != null && this.enableAudit) { messageAudit.rollback(message); } } @Override public boolean isSendToDeadLetterQueue(Message message) { boolean result = false; if (message != null) { result = true; if (enableAudit && messageAudit.isDuplicate(message)) { result = false; LOG.debug("Not adding duplicate to DLQ: {}, dest: {}", message.getMessageId(), message.getDestination()); } if (!message.isPersistent() && !processNonPersistent) { result = false; } if (message.isExpired() && !processExpired) { result = false; } } return result; } /** * @return the processExpired */ @Override public boolean isProcessExpired() { return this.processExpired; } /** * @param processExpired the processExpired to set */ @Override public void setProcessExpired(boolean processExpired) { this.processExpired = processExpired; } /** * @return the processNonPersistent */ @Override public boolean isProcessNonPersistent() { return this.processNonPersistent; } /** * @param processNonPersistent the processNonPersistent to set */ @Override public void setProcessNonPersistent(boolean processNonPersistent) { this.processNonPersistent = processNonPersistent; } public boolean isEnableAudit() { return enableAudit; } public void setEnableAudit(boolean enableAudit) { this.enableAudit = enableAudit; } public long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } public int getMaxProducersToAudit() { return messageAudit.getMaximumNumberOfProducersToTrack(); } public void setMaxProducersToAudit(int maxProducersToAudit) { messageAudit.setMaximumNumberOfProducersToTrack(maxProducersToAudit); } public void setMaxAuditDepth(int maxAuditDepth) { messageAudit.setAuditDepth(maxAuditDepth); } public int getMaxAuditDepth() { return messageAudit.getAuditDepth(); } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 11819 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/region/policy/AbstractDeadLetterStrategy.java/#L29-L127 | 1 | 1730 | 11819 | major | |
| 932 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 932 | 8357 | major | ||
| 2343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 2343 | 14182 | major | ||
| 2098 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | data class, long method | t | t | t | long method | 0 | 13153 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 2098 | 13153 | minor | |
| 1397 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1397 | 10854 | minor | ||
| 2185 | YES I found bad smells the bad smells are: Long method, Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method,Duplicated code,Complex code,Feature envy,Inconsistent naming convention,Unnecessary comments | t | f | t | Duplicated code, Complex code, Feature envy, Inconsistent naming convention, Unnecessary comments. | 0 | 13430 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 2185 | 13430 | major | |
| 1103 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1103 | 9847 | minor | ||
| 2504 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Feature Envy | t | f | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2504 | 14666 | critical | ||
| 897 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | data class | t | t | t | 0 | 8148 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 1 | 897 | 8148 | critical | ||
| 2244 | { "output": "YES I found bad smells. the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | 1. data class | t | t | t | 0 | 13631 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 2244 | 13631 | major | ||
| 1168 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | Long method | t | f | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1168 | 10191 | minor | ||
| 1694 | YES I found bad smells, 1. Long method, 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, 2 Complex conditional logic with multiple nested if statements, 3 Feature envy (internalFuture is accessed multiple times within the get() method), 4 Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5 Mixing of different levels of abstraction (usage of both explicit TimeUnitMILLISECONDS and direct system millisecond calculations) | t | f | t | 2. Complex conditional logic with multiple nested if statements, 3. Feature envy (internalFuture is accessed multiple times within the get() method), 4. Mixing up of different responsibilities (both waiting for internalFuture and getting the result are handled within the get() method), 5. Mixing of different levels of abstraction (usage of both explicit TimeUnit.MILLISECONDS and direct system millisecond calculations) | 0 | 11718 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1694 | 11718 | minor | |
| 960 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | 1. long method | t | t | t | 0 | 8567 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 960 | 8567 | minor | ||
| 745 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 7007 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 745 | 7007 | critical | |
| 1558 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | Blob, Long Method | t | f | t | Long Method | 0 | 11299 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 1 | 1558 | 11299 | major | |
| 2286 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | data class | t | t | t | 0 | 13880 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 2286 | 13880 | major | ||
| 1007 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 9259 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1007 | 9259 | minor | |
| 1747 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long Method | t | f | t | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1747 | 11855 | minor | ||
| 5571 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy."} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
feature envy | 1. long method, 2. feature envy. | t | t | f | 1. long method | feature envy | 0 | 8188 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5571 | 8188 | minor |
| 86 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 86 | 1216 | minor | |
| 1076 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | blob, long method | t | t | t | blob | 0 | 9643 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 1076 | 9643 | major | |
| 2356 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14230 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 2356 | 14230 | critical | ||
| 391 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Duplicate code", "Deeply nested code", "Feature envy", "Data class", "Shotgun surgery" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | long method, duplicate code, deeply nested code, feature envy, data class, shotgun surgery | t | t | f | long method, duplicate code, deeply nested code, feature envy, shotgun surgery | data class | 0 | 3964 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 2 | 391 | 3964 | major |
| 1000 | YES, I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 9174 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 2 | 1000 | 9174 | major | ||
| 2178 | { "response": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } @Override public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } |
data class | data class, long method | t | t | t | long method | 0 | 13410 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-kahadb-store/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java/#L2313-L2340 | 1 | 2178 | 13410 | major | |
| 5507 | The bad smells are: 1.Long Method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method, 2Feature Envy | f | f | t | 2.Feature Envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5507 | 3711 | critical | |
| 2126 | {"message": "YES, I found bad smells.", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class | t | t | t | 0 | 13221 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2126 | 13221 | critical | ||
| 2225 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | \n1. data class | t | t | t | 0 | 13573 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 2225 | 13573 | major | ||
| 1053 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 1053 | 9480 | minor | ||
| 806 | {"message":"YES I found bad smells","detected_bad_smells":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | data class, long method | t | t | t | long method | 0 | 7625 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 806 | 7625 | major | |
| 2558 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14834 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2558 | 14834 | major | |
| 2901 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality. 3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case. 4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods. 5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy - The method is accessing variables from a different class, indicating that it may not be the best class to handle this functionality3 Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case4 Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods5 Large class - The class may have too many responsibilities and could be split into smaller, more focused classes | t | f | t | indicating that it may not be the best class to handle this functionality.3. Repetitive code - The same code for checking the field type and setting the field in the struct is repeated for each case.4. Long switch statement - The switch statement has many cases and could potentially be refactored into smaller, more specialized methods.5. Large class - The class may have too many responsibilities and could be split into smaller, more focused classes. | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 2901 | 2195 | major | |
| 940 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | long method | t | t | t | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 940 | 8460 | major | ||
| 1609 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | 1 Data Class | t | f | t | 0 | 11456 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 1 | 1609 | 11456 | major | ||
| 1029 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Nested loops and conditionals 4. Lack of proper abstraction and encapsulation 5. Inefficient use of Java 8 Streams 6. Use of HashMaps instead of more appropriate data structures 7. Code duplication 8. Unnecessary use of lambdas and method references | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
feature envy | Long method2 Feature envy3 Nested loops and conditionals4 Lack of proper abstraction and encapsulation5 Inefficient use of Java 8 Streams6 Use of HashMaps instead of more appropriate data structures7 Code duplication8 Unnecessary use of lambdas and method references | t | f | t | 0 | 9382 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1029 | 9382 | major | ||
| 2197 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | long method | t | t | t | 0 | 13483 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 2197 | 13483 | minor | ||
| 1926 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1926 | 12438 | major | ||
| 796 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7556 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 2 | 796 | 7556 | minor | ||
| 318 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 2 | 318 | 3262 | critical | ||
| 1441 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 1441 | 10974 | minor | ||
| 945 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8480 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 945 | 8480 | minor | ||
| 3806 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Shotgun surgery 5. Duplicate code 6. Inconsistent formatting 7. Poor naming conventions 8. Magic numbers 9. Hard-coded values 10. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Data class4 Shotgun surgery5 Duplicate code6 Inconsistent formatting7 Poor naming conventions8 Magic numbers9 Hard-coded values | t | f | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 3806 | 9657 | major | ||
| 2211 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Parser { public static GetOrderReferenceDetailsResponseData getOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final GetOrderReferenceDetailsResponse response = marshalXML(GetOrderReferenceDetailsResponse.class, rawResponse); return new GetOrderReferenceDetailsResponseData(response, rawResponse); } public static SetOrderReferenceDetailsResponseData setOrderReferenceDetails(ResponseData rawResponse) throws AmazonServiceException { final SetOrderReferenceDetailsResponse response = marshalXML(SetOrderReferenceDetailsResponse.class, rawResponse); return new SetOrderReferenceDetailsResponseData(response, rawResponse); } public static AuthorizeResponseData getAuthorizeData(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeResponse response = marshalXML(AuthorizeResponse.class, rawResponse); return new AuthorizeResponseData(response, rawResponse); } public static GetAuthorizationDetailsResponseData getAuthorizationDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetAuthorizationDetailsResponse response = marshalXML(GetAuthorizationDetailsResponse.class, rawResponse); return new GetAuthorizationDetailsResponseData(response, rawResponse); } public static CaptureResponseData getCapture(ResponseData rawResponse) throws AmazonServiceException { final CaptureResponse response = marshalXML(CaptureResponse.class, rawResponse); return new CaptureResponseData(response, rawResponse); } public static GetCaptureDetailsResponseData getCaptureDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetCaptureDetailsResponse response = marshalXML(GetCaptureDetailsResponse.class, rawResponse); return new GetCaptureDetailsResponseData(response, rawResponse); } public static ConfirmOrderReferenceResponseData confirmOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ConfirmOrderReferenceResponse response = marshalXML(ConfirmOrderReferenceResponse.class, rawResponse); return new ConfirmOrderReferenceResponseData(response, rawResponse); } public static CloseAuthorizationResponseData closeAuthorizationResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseAuthorizationResponse response = marshalXML(CloseAuthorizationResponse.class, rawResponse); return new CloseAuthorizationResponseData(response, rawResponse); } public static CancelOrderReferenceResponseData getCancelOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CancelOrderReferenceResponse response = marshalXML(CancelOrderReferenceResponse.class, rawResponse); return new CancelOrderReferenceResponseData(response, rawResponse); } public static CloseOrderReferenceResponseData getCloseOrderReference(ResponseData rawResponse) throws AmazonServiceException { final CloseOrderReferenceResponse response = marshalXML(CloseOrderReferenceResponse.class, rawResponse); return new CloseOrderReferenceResponseData(response, rawResponse); } public static RefundResponseData getRefundData(ResponseData rawResponse) throws AmazonServiceException { final RefundResponse response = marshalXML(RefundResponse.class, rawResponse); return new RefundResponseData(response, rawResponse); } public static GetRefundDetailsResponseData getRefundDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetRefundDetailsResponse response = marshalXML(GetRefundDetailsResponse.class, rawResponse); return new GetRefundDetailsResponseData(response, rawResponse); } public static GetBillingAgreementDetailsResponseData getBillingAgreementDetailsData(ResponseData rawResponse) throws AmazonServiceException { final GetBillingAgreementDetailsResponse response = marshalXML(GetBillingAgreementDetailsResponse.class, rawResponse); return new GetBillingAgreementDetailsResponseData(response, rawResponse); } public static SetBillingAgreementDetailsResponseData getSetBillingAgreementDetailsResponse(ResponseData rawResponse) throws AmazonServiceException { final SetBillingAgreementDetailsResponse response = marshalXML(SetBillingAgreementDetailsResponse.class, rawResponse); return new SetBillingAgreementDetailsResponseData(response, rawResponse); } public static ValidateBillingAgreementResponseData getValidateBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ValidateBillingAgreementResponse response = marshalXML(ValidateBillingAgreementResponse.class, rawResponse); return new ValidateBillingAgreementResponseData(response, rawResponse); } public static ConfirmBillingAgreementResponseData confirmBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final ConfirmBillingAgreementResponse response = marshalXML(ConfirmBillingAgreementResponse.class, rawResponse); return new ConfirmBillingAgreementResponseData(response, rawResponse); } public static AuthorizeOnBillingAgreementResponseData getAuthorizeOnBillingAgreement(ResponseData rawResponse) throws AmazonServiceException { final AuthorizeOnBillingAgreementResponse response = marshalXML(AuthorizeOnBillingAgreementResponse.class, rawResponse); return new AuthorizeOnBillingAgreementResponseData(response, rawResponse); } public static CloseBillingAgreementResponseData closeBillingAgreementResponse(ResponseData rawResponse) throws AmazonServiceException { final CloseBillingAgreementResponse response = marshalXML(CloseBillingAgreementResponse.class, rawResponse); return new CloseBillingAgreementResponseData(response, rawResponse); } public static GetProviderCreditDetailsResponseData getGetProviderCreditDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditDetailsResponse response = marshalXML(GetProviderCreditDetailsResponse.class, rawResponse); return new GetProviderCreditDetailsResponseData(response, rawResponse); } public static GetProviderCreditReversalDetailsResponseData getProviderCreditReversalDetails(ResponseData rawResponse) throws AmazonServiceException { final GetProviderCreditReversalDetailsResponse response = marshalXML(GetProviderCreditReversalDetailsResponse.class, rawResponse); return new GetProviderCreditReversalDetailsResponseData(response, rawResponse); } public static ReverseProviderCreditResponseData getReverseProviderCreditResponseData(ResponseData rawResponse) throws AmazonServiceException { final ReverseProviderCreditResponse response = marshalXML(ReverseProviderCreditResponse.class, rawResponse); return new ReverseProviderCreditResponseData(response, rawResponse); } public static GetServiceStatusResponseData getServiceStatus( ResponseData rawResponse) throws AmazonServiceException { final GetServiceStatusResponse response = marshalXML( GetServiceStatusResponse.class, rawResponse); return new GetServiceStatusResponseData(response, rawResponse); } public static CreateOrderReferenceForIdResponseData createOrderReferenceForId( ResponseData rawResponse) throws AmazonServiceException { final CreateOrderReferenceForIdResponse response = marshalXML( CreateOrderReferenceForIdResponse.class, rawResponse); return new CreateOrderReferenceForIdResponseData(response, rawResponse); } public static ListOrderReferenceResponseData listOrderReference(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceResponse response = marshalXML(ListOrderReferenceResponse.class, rawResponse); return new ListOrderReferenceResponseData(response, rawResponse); } public static ListOrderReferenceByNextTokenResponseData listOrderReferenceByNextToken(ResponseData rawResponse) throws AmazonServiceException { final ListOrderReferenceByNextTokenResponse response = marshalXML(ListOrderReferenceByNextTokenResponse.class, rawResponse); return new ListOrderReferenceByNextTokenResponseData(response, rawResponse); } public static SetOrderAttributesResponseData setOrderAttributes(ResponseData rawResponse) throws AmazonServiceException { final SetOrderAttributesResponse response = marshalXML(SetOrderAttributesResponse.class, rawResponse); return new SetOrderAttributesResponseData(response, rawResponse); } public static GetMerchantAccountStatusResponseData getMerchantAccountStatus(ResponseData rawResponse) throws AmazonServiceException { final GetMerchantAccountStatusResponse response = marshalXML(GetMerchantAccountStatusResponse.class, rawResponse); return new GetMerchantAccountStatusResponseData(response, rawResponse); } public static T marshalXML(Class clazz, ResponseData rawResponse) throws AmazonServiceException { try { if (rawResponse.getStatusCode() == 200) { T responseObject = null; final JAXBContext context = JAXBContext.newInstance(clazz); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); responseObject = (T) unmarshaller.unmarshal(xmlStreamReader); return responseObject; } else { generateErrorException(rawResponse); } } catch (JAXBException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } return null; } public static void generateErrorException(ResponseData rawResponse) throws AmazonServiceException, JAXBException { final JAXBContext context = JAXBContext.newInstance(ErrorResponse.class); // Ignore the namespace only for marshalling purpose final String noNamespaceXML = rawResponse.toXML().replaceAll( "xmlns(?:.*?)?=\"http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01\"", ""); final StringReader reader = new StringReader(noNamespaceXML); final Unmarshaller unmarshaller = context.createUnmarshaller(); final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); try { final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader); final ErrorResponse result = (ErrorResponse) unmarshaller.unmarshal(xmlStreamReader); throw new AmazonServiceException(result, rawResponse); } catch (XMLStreamException e) { throw new AmazonClientException(rawResponse, "Encountered marshalling error while marshalling data " + rawResponse.toXML(), e); } } } |
blob | blob, data class | t | t | t | data class | 0 | 13521 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/parser/Parser.java/#L57-L252 | 1 | 2211 | 13521 | major | |
| 108 | { "answer": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 1440 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 108 | 1440 | minor | ||
| 1654 | YES I found bad smells the bad smells are: 1. Feature envy, 2. Long method, 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Feature envy, 2 Long method, 3 Duplicate code | t | f | t | . Feature envy, 3. Duplicate code | 0 | 11585 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 1654 | 11585 | minor | |
| 3842 | YES I found bad smells. 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void transition(JobImpl job, JobEvent event) { job.addDiagnostic(((JobDiagnosticsUpdateEvent) event) .getDiagnosticUpdate()); } |
feature envy | Feature envy | t | f | t | 0 | 9936 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java/#L2115-L2119 | 2 | 3842 | 9936 | minor | ||
| 827 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class SortableASTTransformation extends AbstractASTTransformation { private static final ClassNode MY_TYPE = make(Sortable.class); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode COMPARABLE_TYPE = makeClassSafe(Comparable.class); private static final ClassNode COMPARATOR_TYPE = makeClassSafe(Comparator.class); private static final String VALUE = "value"; private static final String OTHER = "other"; private static final String THIS_HASH = "thisHash"; private static final String OTHER_HASH = "otherHash"; private static final String ARG0 = "arg0"; private static final String ARG1 = "arg1"; public void visit(ASTNode[] nodes, SourceUnit source) { init(nodes, source); AnnotationNode annotation = (AnnotationNode) nodes[0]; AnnotatedNode parent = (AnnotatedNode) nodes[1]; if (parent instanceof ClassNode) { createSortable(annotation, (ClassNode) parent); } } private void createSortable(AnnotationNode anno, ClassNode classNode) { List includes = getMemberStringList(anno, "includes"); List excludes = getMemberStringList(anno, "excludes"); boolean reversed = memberHasValue(anno, "reversed", true); boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true); boolean allNames = memberHasValue(anno, "allNames", true); boolean allProperties = !memberHasValue(anno, "allProperties", false); if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno); } List properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames); implementComparable(classNode); addGeneratedMethod(classNode, "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) ); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); } private static void implementComparable(ClassNode classNode) { if (!classNode.implementsInterface(COMPARABLE_TYPE)) { classNode.addInterface(makeClassSafeWithGenerics(Comparable.class, classNode)); } } private static Statement createCompareToMethodBody(List properties, boolean reversed) { List statements = new ArrayList(); // if (this.is(other)) return 0; statements.add(ifS(callThisX("is", args(OTHER)), returnS(constX(0)))); if (properties.isEmpty()) { // perhaps overkill but let compareTo be based on hashes for commutativity // return this.hashCode() <=> other.hashCode() statements.add(declS(localVarX(THIS_HASH, ClassHelper.Integer_TYPE), callX(varX("this"), "hashCode"))); statements.add(declS(localVarX(OTHER_HASH, ClassHelper.Integer_TYPE), callX(varX(OTHER), "hashCode"))); statements.add(returnS(compareExpr(varX(THIS_HASH), varX(OTHER_HASH), reversed))); } else { // int value = 0; statements.add(declS(localVarX(VALUE, ClassHelper.int_TYPE), constX(0))); for (PropertyNode property : properties) { String propName = property.getName(); // value = this.prop <=> other.prop; statements.add(assignS(varX(VALUE), compareExpr(propX(varX("this"), propName), propX(varX(OTHER), propName), reversed))); // if (value != 0) return value; statements.add(ifS(neX(varX(VALUE), constX(0)), returnS(varX(VALUE)))); } // objects are equal statements.add(returnS(constX(0))); } final BlockStatement body = new BlockStatement(); body.addStatements(statements); return body; } private static Statement createCompareMethodBody(PropertyNode property, boolean reversed) { String propName = property.getName(); return block( // if (arg0 == arg1) return 0; ifS(eqX(varX(ARG0), varX(ARG1)), returnS(constX(0))), // if (arg0 != null && arg1 == null) return -1; ifS(andX(notNullX(varX(ARG0)), equalsNullX(varX(ARG1))), returnS(constX(-1))), // if (arg0 == null && arg1 != null) return 1; ifS(andX(equalsNullX(varX(ARG0)), notNullX(varX(ARG1))), returnS(constX(1))), // return arg0.prop <=> arg1.prop; returnS(compareExpr(propX(varX(ARG0), propName), propX(varX(ARG1), propName), reversed)) ); } private static void createComparatorFor(ClassNode classNode, PropertyNode property, boolean reversed) { String propName = StringGroovyMethods.capitalize((CharSequence) property.getName()); String className = classNode.getName() + "$" + propName + "Comparator"; ClassNode superClass = makeClassSafeWithGenerics(AbstractComparator.class, classNode); InnerClassNode cmpClass = new InnerClassNode(classNode, className, ACC_PRIVATE | ACC_STATIC, superClass); addGeneratedInnerClass(classNode, cmpClass); addGeneratedMethod(cmpClass, "compare", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), ARG0), param(newClass(classNode), ARG1)), ClassNode.EMPTY_ARRAY, createCompareMethodBody(property, reversed) ); String fieldName = "this$" + propName + "Comparator"; // private final Comparator this$Comparator = new $Comparator(); FieldNode cmpField = classNode.addField( fieldName, ACC_STATIC | ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC, COMPARATOR_TYPE, ctorX(cmpClass)); addGeneratedMethod(classNode, "comparatorBy" + propName, ACC_PUBLIC | ACC_STATIC, COMPARATOR_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, returnS(fieldX(cmpField)) ); } private List findProperties(AnnotationNode annotation, final ClassNode classNode, final List includes, final List excludes, final boolean allProperties, final boolean includeSuperProperties, final boolean allNames) { Set names = new HashSet(); List props = getAllProperties(names, classNode, classNode, true, false, allProperties, false, includeSuperProperties, false, false, allNames, false); List properties = new ArrayList(); for (PropertyNode property : props) { String propertyName = property.getName(); if ((excludes != null && excludes.contains(propertyName)) || includes != null && !includes.contains(propertyName)) continue; properties.add(property); } for (PropertyNode pNode : properties) { checkComparable(pNode); } if (includes != null) { Comparator includeComparator = new Comparator() { public int compare(PropertyNode o1, PropertyNode o2) { return Integer.compare(includes.indexOf(o1.getName()), includes.indexOf(o2.getName())); } }; Collections.sort(properties, includeComparator); } return properties; } private void checkComparable(PropertyNode pNode) { if (pNode.getType().implementsInterface(COMPARABLE_TYPE) || isPrimitiveType(pNode.getType()) || hasAnnotation(pNode.getType(), MY_TYPE)) { return; } addError("Error during " + MY_TYPE_NAME + " processing: property '" + pNode.getName() + "' must be Comparable", pNode); } /** * Helper method used to build a binary expression that compares two values * with the option to handle reverse order. */ private static BinaryExpression compareExpr(Expression lhv, Expression rhv, boolean reversed) { return (reversed) ? cmpX(rhv, lhv) : cmpX(lhv, rhv); } } |
data class | data class, long method | t | t | t | long method | 0 | 7725 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/SortableASTTransformation.java/#L82-L265 | 1 | 827 | 7725 | minor | |
| 1311 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1311 | 10681 | critical | ||
| 5561 | { "output": "YES I found bad smells", "bad smells are": "1.Long method, 2.Feature envy" } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | 1.long method, 2.feature envy | t | t | f | 2.feature envy | long method | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 2 | 5561 | 7769 | minor |
| 1462 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TupleImpl extends IndifferentAccessMap implements Seqable, Indexed, IMeta, Tuple { private List values; private int taskId; private String streamId; private GeneralTopologyContext context; private MessageId id; private IPersistentMap _meta = null; Long _processSampleStartTime = null; Long _executeSampleStartTime = null; long _outAckVal = 0; public TupleImpl() { } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId, MessageId id) { this.values = values; this.taskId = taskId; this.streamId = streamId; this.id = id; this.context = context; /* String componentId = context.getComponentId(taskId); Fields schema = context.getComponentOutputFields(componentId, streamId); if (values.size() != schema.size()) { throw new IllegalArgumentException("Tuple created with wrong number of fields. " + "Expected " + schema.size() + " fields but got " + values.size() + " fields"); }*/ } public TupleImpl(GeneralTopologyContext context, List values, int taskId, String streamId) { this(context, values, taskId, streamId, MessageId.makeUnanchored()); } public void setProcessSampleStartTime(long ms) { _processSampleStartTime = ms; } public Long getProcessSampleStartTime() { return _processSampleStartTime; } public void setExecuteSampleStartTime(long ms) { _executeSampleStartTime = ms; } public Long getExecuteSampleStartTime() { return _executeSampleStartTime; } public void updateAckVal(long val) { _outAckVal = _outAckVal ^ val; } public long getAckVal() { return _outAckVal; } public int size() { return values.size(); } public int fieldIndex(String field) { return getFields().fieldIndex(field); } public boolean contains(String field) { return getFields().contains(field); } public Object getValue(int i) { return values.get(i); } public String getString(int i) { return (String) values.get(i); } public Integer getInteger(int i) { return (Integer) values.get(i); } public Long getLong(int i) { return (Long) values.get(i); } public Boolean getBoolean(int i) { return (Boolean) values.get(i); } public Short getShort(int i) { return (Short) values.get(i); } public Byte getByte(int i) { return (Byte) values.get(i); } public Double getDouble(int i) { return (Double) values.get(i); } public Float getFloat(int i) { return (Float) values.get(i); } public byte[] getBinary(int i) { return (byte[]) values.get(i); } public Object getValueByField(String field) { return values.get(fieldIndex(field)); } public String getStringByField(String field) { return (String) values.get(fieldIndex(field)); } public Integer getIntegerByField(String field) { return (Integer) values.get(fieldIndex(field)); } public Long getLongByField(String field) { return (Long) values.get(fieldIndex(field)); } public Boolean getBooleanByField(String field) { return (Boolean) values.get(fieldIndex(field)); } public Short getShortByField(String field) { return (Short) values.get(fieldIndex(field)); } public Byte getByteByField(String field) { return (Byte) values.get(fieldIndex(field)); } public Double getDoubleByField(String field) { return (Double) values.get(fieldIndex(field)); } public Float getFloatByField(String field) { return (Float) values.get(fieldIndex(field)); } public byte[] getBinaryByField(String field) { return (byte[]) values.get(fieldIndex(field)); } public List getValues() { return values; } public Fields getFields() { return context.getComponentOutputFields(getSourceComponent(), getSourceStreamId()); } public List select(Fields selector) { return getFields().select(selector, values); } public GlobalStreamId getSourceGlobalStreamid() { return new GlobalStreamId(getSourceComponent(), streamId); } public String getSourceComponent() { return context.getComponentId(taskId); } public int getSourceTask() { return taskId; } public String getSourceStreamId() { return streamId; } public MessageId getMessageId() { return id; } @Override public String toString() { return "source: " + getSourceComponent() + ":" + taskId + ", stream: " + streamId + ", id: " + id.toString() + ", " + values.toString(); } @Override public boolean equals(Object other) { return this == other; } @Override public int hashCode() { return System.identityHashCode(this); } private Keyword makeKeyword(String name) { return Keyword.intern(Symbol.create(name)); } /* ILookup */ @Override public Object valAt(Object o) { try { if (o instanceof Keyword) { return getValueByField(((Keyword) o).getName()); } else if (o instanceof String) { return getValueByField((String) o); } } catch (IllegalArgumentException ignored) { } return null; } /* Seqable */ public ISeq seq() { if (values.size() > 0) { return new Seq(getFields().toList(), values, 0); } return null; } static class Seq extends ASeq implements Counted { final List fields; final List values; final int i; Seq(List fields, List values, int i) { this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Seq(IPersistentMap meta, List fields, List values, int i) { super(meta); this.fields = fields; this.values = values; assert i >= 0; this.i = i; } public Object first() { return new MapEntry(fields.get(i), values.get(i)); } public ISeq next() { if (i + 1 < fields.size()) { return new Seq(fields, values, i + 1); } return null; } public int count() { assert fields.size() - i >= 0 : "index out of bounds"; // i being the position in the fields of this seq, the remainder of the seq is the size return fields.size() - i; } public Obj withMeta(IPersistentMap meta) { return new Seq(meta, fields, values, i); } } /* Indexed */ public Object nth(int i) { if (i < values.size()) { return values.get(i); } else { return null; } } public Object nth(int i, Object notfound) { Object ret = nth(i); if (ret == null) ret = notfound; return ret; } /* Counted */ public int count() { return values.size(); } /* IMeta */ public IPersistentMap meta() { if (_meta == null) { _meta = new PersistentArrayMap(new Object[]{makeKeyword("stream"), getSourceStreamId(), makeKeyword("component"), getSourceComponent(), makeKeyword("task"), getSourceTask()}); } return _meta; } private PersistentArrayMap toMap() { Object array[] = new Object[values.size() * 2]; List fields = getFields().toList(); for (int i = 0; i < values.size(); i++) { array[i * 2] = fields.get(i); array[(i * 2) + 1] = values.get(i); } return new PersistentArrayMap(array); } public IPersistentMap getMap() { if (_map == null) { setMap(toMap()); } return _map; } public void setTopologyContext(GeneralTopologyContext context) { this.context = context; } public GeneralTopologyContext getTopologyContext() { return context; } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 11026 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/tuple/TupleImpl.java/#L37-L356 | 1 | 1462 | 11026 | major | |
| 281 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | long method | t | t | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 1 | 281 | 3011 | minor | ||
| 280 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | data class | t | t | t | 0 | 3003 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 1 | 280 | 3003 | minor | ||
| 2683 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | long method, blob | t | t | t | blob | 0 | 15269 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 2683 | 15269 | minor | |
| 1748 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
blob | Blob, Data Class, Long Method | t | f | t | Data Class, Long Method | 0 | 11856 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 1748 | 11856 | major | |
| 1644 | YES I found bad smells The bad smells are: 1. Long method 2. Magic numbers 3. Complex conditionals 4. Feature envy 5. Large switch statement 6. Hard-coded values 7. Bad exception handling 8. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Magic numbers3 Complex conditionals4 Feature envy5 Large switch statement6 Hard-coded values7 Bad exception handling8 Code duplication | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1644 | 11558 | major | ||
| 2965 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OptionSet implements UaStructure { public static final NodeId TypeId = Identifiers.OptionSet; public static final NodeId BinaryEncodingId = Identifiers.OptionSet_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.OptionSet_Encoding_DefaultXml; protected final ByteString value; protected final ByteString validBits; public OptionSet() { this.value = null; this.validBits = null; } public OptionSet(ByteString value, ByteString validBits) { this.value = value; this.validBits = validBits; } public ByteString getValue() { return value; } public ByteString getValidBits() { return validBits; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("Value", value) .add("ValidBits", validBits) .toString(); } public static class Codec extends BuiltinDataTypeCodec { @Override public Class getType() { return OptionSet.class; } @Override public OptionSet decode(UaDecoder decoder) throws UaSerializationException { ByteString value = decoder.readByteString("Value"); ByteString validBits = decoder.readByteString("ValidBits"); return new OptionSet(value, validBits); } @Override public void encode(OptionSet value, UaEncoder encoder) throws UaSerializationException { encoder.writeByteString("Value", value.value); encoder.writeByteString("ValidBits", value.validBits); } } } |
data class | data class, long method | t | t | t | long method | 0 | 2728 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-stack/stack-core/src/main/java/org/eclipse/milo/opcua/stack/core/types/structured/OptionSet.java/#L23-L85 | 1 | 2965 | 2728 | minor | |
| 1004 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9254 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1004 | 9254 | major | ||
| 333 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static boolean checkExplicitUserPassword(ManagementContext mgmt, String user, String password) { BrooklynProperties properties = ((ManagementContextInternal)mgmt).getBrooklynProperties(); String expectedPassword = properties.getConfig(BrooklynWebConfig.PASSWORD_FOR_USER(user)); String salt = properties.getConfig(BrooklynWebConfig.SALT_FOR_USER(user)); String expectedSha256 = properties.getConfig(BrooklynWebConfig.SHA256_FOR_USER(user)); return checkPassword(password, expectedPassword, expectedSha256, salt); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 3421 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/rest/rest-server/src/main/java/org/apache/brooklyn/rest/security/provider/ExplicitUsersSecurityProvider.java/#L94-L101 | 1 | 333 | 3421 | minor |
| 1576 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | Data Class | t | f | t | 0 | 11350 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 1 | 1576 | 11350 | major | ||
| 2414 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 14415 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 2414 | 14415 | minor | |
| 2612 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class, long method | t | t | t | long method | 0 | 15042 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 2612 | 15042 | major | |
| 1837 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code. 3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers. 4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code. 5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method. 6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring. 7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication. 8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand. 9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long method2 Feature envy: the NormalizeResutlSetNode class is accessing methods and data from other classes, including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code3 Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers4 Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code5 Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method6 Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring7 Code duplication: some lines of code, such as "chldResgetResultColumns()", are duplicated in different parts of the code, indicating code duplication8 Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand9 Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation | t | f | t | including chldRes, targetResultColumnList, and ResultColumnList, which suggests that feature envy is present in this code.3. Magic numbers: the use of constants, such as "true" and "false" in boolean expressions, suggests the presence of magic numbers.4. Poor naming conventions: variable and method names are not descriptive enough, making it difficult to understand the purpose of each piece of code.5. Lack of comments/documentation: there are few comments in the code, making it difficult to understand the purpose and functionality of each method.6. Complex/unnecessary logic: the code could be simplified and made more efficient through refactoring.7. Code duplication: some lines of code, such as "chldRes.getResultColumns()", are duplicated in different parts of the code, indicating code duplication.8. Inconsistent formatting: the indentations and spacing are inconsistent throughout the code, making it difficult to read and understand.9. Violation of encapsulation: some methods, such as "setResultColumns()", are accessing private data from other classes, breaking the principle of encapsulation. | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 1837 | 12142 | minor | |
| 1207 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | data class, long method | t | t | t | data class | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 1207 | 10290 | major | |
| 1354 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | data class | t | t | t | 0 | 10763 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 1 | 1354 | 10763 | minor | ||
| 2212 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FilterParams { private final Collection filterByStatus; private final Boolean overdueState; private final String filterBySearchText; private final Boolean selectTargetWithNoTag; private final String[] filterByTagNames; private final Long filterByDistributionId; /** * Constructor. * * @param filterByInstalledOrAssignedDistributionSetId * if set, a filter is added for the given * {@link DistributionSet#getId()} * @param filterByStatus * if set, a filter is added for target states included by the * collection * @param overdueState * if set, a filter is added for overdued devices * @param filterBySearchText * if set, a filter is added for the given search text * @param selectTargetWithNoTag * if set, tag-filtering is enabled * @param filterByTagNames * if tag-filtering is enabled, a filter is added for the given * tag-names */ public FilterParams(final Collection filterByStatus, final Boolean overdueState, final String filterBySearchText, final Long filterByInstalledOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { this.filterByStatus = filterByStatus; this.overdueState = overdueState; this.filterBySearchText = filterBySearchText; this.filterByDistributionId = filterByInstalledOrAssignedDistributionSetId; this.selectTargetWithNoTag = selectTargetWithNoTag; this.filterByTagNames = filterByTagNames; } /** * Gets {@link DistributionSet#getId()} to filter the result. * If set to null this filter is disabled. * * @return {@link DistributionSet#getId()} to filter the result */ public Long getFilterByDistributionId() { return filterByDistributionId; } /** * Gets a collection of target states to filter for. * If set to null this filter is disabled. * * @return collection of target states to filter for */ public Collection getFilterByStatus() { return filterByStatus; } /** * Gets the flag for overdue filter; if set to true, the * overdue filter is activated. Overdued targets a targets that did not * respond during the configured intervals: poll_itvl + overdue_itvl. * If set to null this filter is disabled. * * @return flag for overdue filter activation */ public Boolean getOverdueState() { return overdueState; } /** * Gets the search text to filter for. This is used to find targets having * the text anywhere in name or description * If set to null this filter is disabled. * * @return the search text to filter for */ public String getFilterBySearchText() { return filterBySearchText; } /** * Gets the flag indicating if tagging filter is used. * If set to null this filter is disabled. * * @return the flag indicating if tagging filter is used */ public Boolean getSelectTargetWithNoTag() { return selectTargetWithNoTag; } /** * Gets the tags that are used to filter for. The activation of this filter * is done by {@link #setSelectTargetWithNoTag(Boolean)}. * * @return the tags that are used to filter for */ public String[] getFilterByTagNames() { return filterByTagNames; } } |
data class | data class, long method | t | t | t | long method | 0 | 13524 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/FilterParams.java/#L22-L123 | 1 | 2212 | 13524 | minor | |
| 2572 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | long method, data class | t | t | t | long method | 0 | 14907 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 1 | 2572 | 14907 | minor | |
| 1138 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 10070 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1138 | 10070 | major | ||
| 871 | {"response": "YES, I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | blob, data class | t | t | t | blob | 0 | 7972 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 1 | 871 | 7972 | minor | |
| 1942 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1942 | 12499 | major | ||
| 1731 | YES, I found bad smells the bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 11820 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 1731 | 11820 | major | |
| 2104 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | bad_smell: long method | t | t | f | long method | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 2104 | 13168 | minor | |
| 3840 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | long method | t | t | t | 0 | 9895 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 1 | 3840 | 9895 | major | ||
| 3925 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Inappropriate intimacy 5. Message chain 6. Duplicated code 7. Magic numbers 8. Data class 9. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | Long method 2 Feature envy 3 Primitive obsession 4 Inappropriate intimacy 5 Message chain 6 Duplicated code 7 Magic numbers 8 Data class 9 Lazy class | t | f | t | 0 | 10274 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 2 | 3925 | 10274 | critical | ||
| 505 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void unitKept(IInstallableUnit unit) { super.unitKept(unit); logger.debug(" Keeping unit " + unit.getId() + "/" + unit.getVersion()); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5129 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-bundles/org.eclipse.tycho.p2.resolver.impl/src/main/java/org/eclipse/tycho/p2/target/filters/TargetPlatformFilterEvaluator.java/#L287-L291 | 1 | 505 | 5129 | major |
| 5722 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 12971 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 1 | 5722 | 12971 | minor | ||
| 5382 | { "output": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | data class | t | t | t | 0 | 15137 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 5382 | 15137 | minor | ||
| 664 | { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 6459 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 664 | 6459 | minor | |
| 2029 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Magic strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method, 2Magic numbers, 3Magic strings | t | f | t | 2.Magic numbers, 3.Magic strings | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 2029 | 12807 | minor | |
| 853 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | long method, data class | t | t | t | long method | 0 | 7877 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 853 | 7877 | major | |
| 4011 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10604 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 4011 | 10604 | minor | |
| 5690 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long method", "Long parameter list" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, long parameter list | t | t | t | long parameter list | 0 | 12064 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5690 | 12064 | major | |
| 1766 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | Data Class | t | f | t | 0 | 11911 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 1 | 1766 | 11911 | minor | ||
| 3548 | { "input_code": "public class Example {\n private int x;\n private int y;\n\n public Example(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public int calculateSum() {\n return x + y;\n }\n}", "detected_bad_smells": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | yes i found bad smells the bad smells are: 1. long method | t | t | t | 0 | 7729 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 3548 | 7729 | minor | ||
| 1636 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11525 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 1636 | 11525 | minor | ||
| 413 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OsgiRequirementAdapter implements Requirement { private static final Logger logger = LoggerFactory.getLogger(OsgiRequirementAdapter.class); private final org.osgi.resource.Requirement requirement; public OsgiRequirementAdapter(org.osgi.resource.Requirement requirement) { if (requirement == null) throw new NullPointerException("Missing required parameter: requirement"); this.requirement = requirement; } public String getComment() { return null; } public String getFilter() { return requirement.getDirectives().get(Constants.FILTER_DIRECTIVE); } public String getName() { return NamespaceTranslator.translate(requirement.getNamespace()); } public boolean isExtend() { return false; } public boolean isMultiple() { String multiple = requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE); return Namespace.CARDINALITY_MULTIPLE.equals(multiple); } public boolean isOptional() { String resolution = requirement.getDirectives().get(Constants.RESOLUTION_DIRECTIVE); return Constants.RESOLUTION_OPTIONAL.equals(resolution); } public boolean isSatisfied(Capability capability) { logger.debug(LOG_ENTRY, "isSatisfied", capability); boolean result = ResourceHelper.matches(requirement, new FelixCapabilityAdapter(capability, null)); logger.debug(LOG_EXIT, "isSatisfied", result); return result; } } |
data class | data class, long method | t | t | t | long method | 0 | 4217 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-obr/src/main/java/org/apache/aries/subsystem/util/felix/OsgiRequirementAdapter.java/#L28-L72 | 1 | 413 | 4217 | major | |
| 709 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 709 | 6757 | major | ||
| 1548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1548 | 11258 | minor | |
| 1435 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1435 | 10960 | major | ||
| 543 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5544 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 543 | 5544 | minor |
| 1956 | { "response": "YES, I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | long method | t | t | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 1 | 1956 | 12558 | minor | ||
| 1459 | YES, I found bad smells the bad smells are: 1. Long method 2. Commented out code 3. Use of try-catch without any specific exception handling 4. Use of magic numbers/constant values 5. Feature envy (multiple methods making use of metrics from ClusterMetrics class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Commented out code3 Use of try-catch without any specific exception handling4 Use of magic numbers/constant values5 Feature envy (multiple methods making use of metrics from ClusterMetrics class) | t | f | t | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1459 | 11020 | minor | ||
| 1352 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10761 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 1352 | 10761 | minor | ||
| 1787 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11981 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 1787 | 11981 | minor | ||
| 2691 | { "output": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ScanOptions extends CommonOpts { @Parameter(names = "-s", description = "Start row (inclusive) of scan") private String startRow; @Parameter(names = "-e", description = "End row (inclusive) of scan") private String endRow; @Parameter(names = "-c", description = "Columns of scan in comma separated format: " + "<[:]{,[:]}> ") private List columns; @Parameter(names = "-r", description = "Exact row to scan") private String exactRow; @Parameter(names = "-p", description = "Row prefix to scan") private String rowPrefix; @Parameter(names = {"-esc", "--escape-non-ascii"}, help = true, description = "Hex encode non ascii bytes", arity = 1) public boolean hexEncNonAscii = true; @Parameter(names = "--raw", help = true, description = "Show underlying key/values stored in Accumulo. Interprets the data using Fluo " + "internal schema, making it easier to comprehend.") public boolean scanAccumuloTable = false; @Parameter(names = "--json", help = true, description = "Export key/values stored in Accumulo as JSON file.") public boolean exportAsJson = false; @Parameter(names = "--ntfy", help = true, description = "Scan active notifications") public boolean scanNtfy = false; public String getStartRow() { return startRow; } public String getEndRow() { return endRow; } public String getExactRow() { return exactRow; } public String getRowPrefix() { return rowPrefix; } public List getColumns() { if (columns == null) { return Collections.emptyList(); } return columns; } /** * Check if the parameters informed can be used together. */ private void checkScanOptions() { if (this.scanAccumuloTable && this.exportAsJson) { throw new IllegalArgumentException( "Both \"--raw\" and \"--json\" can not be set together."); } if (this.scanAccumuloTable && this.scanNtfy) { throw new IllegalArgumentException( "Both \"--raw\" and \"--ntfy\" can not be set together."); } } public ScanUtil.ScanOpts getScanOpts() { EnumSet flags = EnumSet.noneOf(ScanFlags.class); ScanUtil.setFlag(flags, help, ScanFlags.HELP); ScanUtil.setFlag(flags, hexEncNonAscii, ScanFlags.HEX); ScanUtil.setFlag(flags, scanAccumuloTable, ScanFlags.ACCUMULO); ScanUtil.setFlag(flags, exportAsJson, ScanFlags.JSON); ScanUtil.setFlag(flags, scanNtfy, ScanFlags.NTFY); return new ScanUtil.ScanOpts(startRow, endRow, columns, exactRow, rowPrefix, flags); } public static ScanOptions parse(String[] args) { ScanOptions opts = new ScanOptions(); parse("fluo scan", opts, args); return opts; } } |
data class | 1: data class, 2: long method | t | t | t | 2: long method | 0 | 15300 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/command/src/main/java/org/apache/fluo/command/FluoScan.java/#L33-L122 | 1 | 2691 | 15300 | minor | |
| 3912 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 10243 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 3912 | 10243 | minor | ||
| 634 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean isValid(Document xml) throws SAXException{ try{ String language = "http://www.w3.org/2001/XMLSchema"; SchemaFactory factory = SchemaFactory.newInstance(language); Source source = new DOMSource(map.getSchema()); Schema schema = factory.newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(xml)); //if no exceptions where raised, the document is valid return true; } catch(IOException e) { LOG.log(POILogger.ERROR, "document is not valid", e); } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6296 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java/#L243-L260 | 2 | 634 | 6296 | minor | ||
| 1376 | { "response": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | 1. data class | t | t | t | 0 | 10810 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 1376 | 10810 | major | ||
| 1420 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1420 | 10928 | minor | |
| 1078 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | 1. long method | t | t | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 1 | 1078 | 9647 | minor | ||
| 1222 | YES I found bad smells the bad smells are: Long method, Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 10338 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 1222 | 10338 | minor | |
| 990 | YES I found bad smells, the bad smells are: 1. Long method, 2. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class MigrationLink { int source; int target; Migration[] migrations; public MigrationLink(int source, int target, Migration[] migrations) { this.source = source; this.target = target; this.migrations = migrations; } } |
data class | Long method, 2 Data class | t | f | t | . Long method | 0 | 9019 | https://github.com/apache/ode/blob/b2ddc6436891f84f716ffcbed8c1cd1e374bd805/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java/#L113-L122 | 2 | 990 | 9019 | major | |
| 1278 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple if statements in a row 4. Hardcoded values for class types, which could lead to maintenance issues if types change in the future 5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy3 Multiple if statements in a row4 Hardcoded values for class types, which could lead to maintenance issues if types change in the future5 Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | t | f | t | which could lead to maintenance issues if types change in the future5. Throwing general exception instead of specific exceptions for each case, which could make it harder to handle errors | 0 | 10592 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1278 | 10592 | minor | |
| 287 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | 1. long method | t | t | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 1 | 287 | 3060 | minor | ||
| 4359 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method | t | t | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 4359 | 11504 | minor | ||
| 4237 | { "output": "YES I found bad smells", "detectedBadSmells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Subchannel extends Pipe { /** * * Number of fuel rods contained within. * * */ private int numRods; /** * * Diameter of the subchannel fuel rods (this assumes uniform rod sizes). * * */ private double rodDiameter; /** * * Pitch of the fuel rod bundle (distance between adjacent rod centers). * * */ private double pitch; /** * * Nullary constructor. * * */ public Subchannel() { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(1); setRodDiameter(1.0); setPitch(1.5); // Note: Pitch must always be set after diameter, as setPitch method // checks that pitch >= rodDiameter. return; } /** * * Parameterized constructor. * * * @param numRods * * Number of rods contained. * * @param rodDiameter * * Diameter of the (uniformly-sized) fuel rods. * * @param pitch * * Pitch of the fuel rods. * */ public Subchannel(int numRods, double rodDiameter, double pitch) { // Set the name, description and ID. setName("Subchannel 1"); setDescription("A subchannel plant component for reactors"); setId(1); // Set the default number of rods, rod diameter and pitch. setNumRods(numRods); setRodDiameter(rodDiameter); setPitch(pitch); return; } /** * @return the numRods */ public int getNumRods() { return numRods; } /** * @param numRods * the numRods to set */ public void setNumRods(int numRods) { // Check the input is valid. if (numRods >= 1) { this.numRods = numRods; } else { throw new InvalidParameterException("Subchannel error: The number " + "of rods must greater than or equal to 1."); } return; } /** * @return the rodDiameter */ public double getRodDiameter() { return rodDiameter; } /** * @param rodDiameter * the rodDiameter to set */ public void setRodDiameter(double rodDiameter) { // Check the input is valid. if (rodDiameter > 0) { this.rodDiameter = rodDiameter; } else { throw new InvalidParameterException("Subchannel error: The rod " + "diameter must be non-negative."); } return; } /** * @return the pitch */ public double getPitch() { return pitch; } /** * @param pitch * the pitch to set */ public void setPitch(double pitch) { // Check that the input is valid. if (pitch >= rodDiameter) { this.pitch = pitch; } else { throw new InvalidParameterException("Subchannel error: The rod " + "pitch cannot be smaller than the rod diameter."); } } /** * * Performs an equality check between two Objects. * * * @param otherObject * * The other Object to compare against. * * @return * Returns true if the two objects are equal, otherwise false. * */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof Subchannel) { // Cast the other object. Subchannel component = (Subchannel) otherObject; // Compare all the variables. (Save the biggest for last; Java // should // short-circuit the logical operators as soon as a mismatch is // found) equals = (super.equals(component) && numRods == component.numRods && rodDiameter == component.rodDiameter && pitch == component.pitch); } return equals; } /** * * Performs a deep copy and returns a newly instantiated Object. * * * @return * The newly instantiated Object. * */ @Override public Object clone() { // Initialize a new object. Subchannel object = new Subchannel(); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * * Deep copies the contents of otherObject. * * * @param otherObject * * The other object to copy the contents from. * */ public void copy(Subchannel otherObject) { // Check the otherObject is valid. if (otherObject == null) { return; } // Copy the other object. super.copy(otherObject); numRods = otherObject.numRods; rodDiameter = otherObject.rodDiameter; pitch = otherObject.pitch; return; } /** * * Returns the hashCode of the object. * * * @return * The hashCode of the Object. * */ @Override public int hashCode() { // Call the super's hashCode. int hash = super.hashCode(); // Add local hashes. hash = 31 * hash + numRods; hash = 31 * hash + new Double(rodDiameter).hashCode(); hash = 31 * hash + new Double(pitch).hashCode(); return hash; } /** * * Accepts PlantComponentVisitors to reveal the type of a PlantComponent. * * * @param visitor * * The PlantComponent's visitor. * */ @Override public void accept(IPlantComponentVisitor visitor) { // Only accept valid visitors. if (visitor != null) { visitor.visit(this); } return; } } |
data class | data class | t | t | t | 0 | 11155 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.reactor.plant/src/org/eclipse/ice/reactor/plant/Subchannel.java/#L25-L303 | 1 | 4237 | 11155 | minor | ||
| 5676 | YES I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 11770 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5676 | 11770 | minor | ||
| 5535 | YES I found bad smells the bad smells are: Data class, Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | Data class, Long method | t | f | t | Data class | 0 | 6189 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5535 | 6189 | major | |
| 5773 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5773 | 14885 | minor | ||
| 1687 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | Long Method | t | f | t | 0 | 11691 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 1687 | 11691 | major | ||
| 2318 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class | t | t | t | 0 | 14124 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 2318 | 14124 | minor | ||
| 4239 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 4239 | 11159 | minor | ||
| 217 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class | t | t | t | 0 | 2368 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 217 | 2368 | major | ||
| 1785 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long Method | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 1785 | 11978 | minor | ||
| 2158 | { "message": "YES I found bad smells. the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionDescriptor extends Descriptor { /** Type token for ser/de partition descriptor list */ private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken>(){}.getType(); @Getter private final DatasetDescriptor dataset; public PartitionDescriptor(String name, DatasetDescriptor dataset) { super(name); this.dataset = dataset; } @Override public PartitionDescriptor copy() { return new PartitionDescriptor(getName(), dataset); } public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) { return new PartitionDescriptor(getName(), dataset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionDescriptor that = (PartitionDescriptor) o; return dataset.equals(that.dataset) && getName().equals(that.getName()); } @Override public int hashCode() { int result = dataset.hashCode(); result = 31 * result + getName().hashCode(); return result; } /** * Serialize a list of partition descriptors as json string */ public static String toPartitionJsonList(List descriptors) { return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE); } /** * Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors */ public static List fromPartitionJsonList(String jsonList) { return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE); } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13316 | https://github.com/apache/incubator-gobblin/blob/b0d130757669a5fed7c368d44f23f8a9c0d3ed4a/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java/#L32-L87 | 1 | 2158 | 13316 | minor | |
| 1737 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11831 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 1 | 1737 | 11831 | minor | |
| 30 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 719 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 30 | 719 | critical | |
| 1212 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
data class | data class, long method | t | t | t | long method | 0 | 10312 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 1 | 1212 | 10312 | minor | |
| 5759 | YES, I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 14515 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5759 | 14515 | major | ||
| 469 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1.": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | 1.: long method | t | t | t | 0 | 4555 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 469 | 4555 | major | ||
| 261 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method, data class | t | t | t | data class | 0 | 2843 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 261 | 2843 | major | |
| 495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 2 | 495 | 5014 | minor | |
| 977 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NodeValueString extends NodeValue { // A plain string, with no language tag, or an xsd:string. private String string ; public NodeValueString(String str) { string = str ; } public NodeValueString(String str, Node n) { super(n) ; string = str ; } @Override public boolean isString() { return true ; } @Override public String getString() { return string ; } @Override public String asString() { return string ; } @Override public String toString() { if ( getNode() != null ) { // Can be a plain string or an xsd:string. return FmtUtils.stringForNode(getNode()) ; } return '"'+string+'"' ; } @Override protected Node makeNode() { return NodeFactory.createLiteral(string) ; } @Override public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; } } |
data class | data class | t | t | t | 0 | 8825 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/NodeValueString.java/#L27-L62 | 1 | 977 | 8825 | minor | ||
| 3557 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 7777 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 3557 | 7777 | major | ||
| 648 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 6380 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceHeader.java/#L127-L138 | 1 | 648 | 6380 | minor | |
| 959 | YES, I found bad smells: 1. Long method 2. Feature envy 3. Data clumps 4. Primitive obsession 5. Inconsistent naming conventions 6. Duplicate code 7. Poor exception handling 8. Tight coupling 9. Multiple responsibilities 10. Lack of proper abstraction | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | Long method2 Feature envy3 Data clumps4 Primitive obsession5 Inconsistent naming conventions6 Duplicate code7 Poor exception handling8 Tight coupling9 Multiple responsibilities | t | f | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 959 | 8560 | minor | ||
| 845 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 845 | 7823 | minor | ||
| 4487 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 4487 | 11883 | major | |
| 2447 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Duplicate code3 Feature Envy | t | f | t | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 2447 | 14497 | minor | ||
| 5710 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5710 | 12666 | major | ||
| 98 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _BuildWebServiceSoap_UpdateBuildDefinitions implements ElementSerializable { // No attributes // Elements protected _BuildDefinition[] updates; public _BuildWebServiceSoap_UpdateBuildDefinitions() { super(); } public _BuildWebServiceSoap_UpdateBuildDefinitions(final _BuildDefinition[] updates) { // TODO : Call super() instead of setting all fields directly? setUpdates(updates); } public _BuildDefinition[] getUpdates() { return this.updates; } public void setUpdates(_BuildDefinition[] value) { this.updates = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.updates != null) { /* * The element type is an array. */ writer.writeStartElement("updates"); for (int iterator0 = 0; iterator0 < this.updates.length; iterator0++) { this.updates[iterator0].writeAsElement( writer, "BuildDefinition"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 1293 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_BuildWebServiceSoap_UpdateBuildDefinitions.java/#L45-L101 | 1 | 98 | 1293 | minor | |
| 2642 | {"message": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | data class | t | t | t | 0 | 15145 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 2642 | 15145 | major | ||
| 445 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Long Method" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | the bad smells are: long method | t | t | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 1 | 445 | 4346 | minor | ||
| 2699 | { "output": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 2699 | 15326 | minor | |
| 1389 | YES I found bad smells the bad smells are: 1.Feature envy,2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Feature envy,2Long method | t | f | t | 2.Long method | 0 | 10840 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1389 | 10840 | major | |
| 3348 | YES I found bad smells. The bad smells are: Feature envy, Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
feature envy | Feature envy, Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | t | f | t | Long method, Duplicate code, Complex method, Unnecessary comments, Indecent exposure, Inappropriate intimacy, Switch statement, Magic numbers, Primitive obsession, God class, Lazy class | 0 | 6306 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 3348 | 6306 | major | |
| 1797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 1797 | 12001 | major | ||
| 1422 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method", "2. Blob", "3. Data Class", "4. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public static final String PLUGIN_NAME_KEY = "pluginName"; public static final String PLUGIN_VERSION_KEY = "pluginVersion"; public static final String INSTALLATION_ID_KEY = "installationId"; public static final String SESSION_ID_KEY = "sessionId"; public static final String SUBSCRIPTION_ID_KEY = "subscriptionId"; public static final String AUTH_TYPE = "authType"; public static final String TELEMETRY_NOT_ALLOWED = "TelemetryNotAllowed"; public static final String INIT_FAILURE = "InitFailure"; public static final String AZURE_INIT_FAIL = "Failed to authenticate with Azure. Please check your configuration."; public static final String FAILURE_REASON = "failureReason"; private static final String CONFIGURATION_PATH = Paths.get(System.getProperty("user.home"), ".azure", "mavenplugins.properties").toString(); private static final String FIRST_RUN_KEY = "first.run"; private static final String PRIVACY_STATEMENT = "\nData/Telemetry\n" + "---------\n" + "This project collects usage data and sends it to Microsoft to help improve our products and services.\n" + "Read Microsoft's privacy statement to learn more: https://privacy.microsoft.com/en-us/privacystatement." + "\n\nYou can change your telemetry configuration through 'allowTelemetry' property.\n" + "For more information, please go to https://aka.ms/azure-maven-config.\n"; //region Properties @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) protected File buildDirectory; @Parameter(defaultValue = "${plugin}", readonly = true, required = true) protected PluginDescriptor plugin; /** * The system settings for Maven. This is the instance resulting from * merging global and user-level settings files. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) protected Settings settings; @Component(role = MavenResourcesFiltering.class, hint = "default") protected MavenResourcesFiltering mavenResourcesFiltering; /** * Authentication setting for Azure Management API. * Below are the supported sub-elements within {@code }. You can use one of them to authenticate * with azure * {@code } specifies the credentials of your Azure service principal, by referencing a server definition * in Maven's settings.xml * {@code } specifies the absolute path of your authentication file for Azure. * * @since 0.1.0 */ @Parameter protected AuthenticationSetting authentication; /** * Azure subscription Id. You only need to specify it when: * * you are using authentication file * there are more than one subscription in the authentication file * * * @since 0.1.0 */ @Parameter protected String subscriptionId = ""; /** * Boolean flag to turn on/off telemetry within current Maven plugin. * * @since 0.1.0 */ @Parameter(property = "allowTelemetry", defaultValue = "true") protected boolean allowTelemetry; /** * Boolean flag to control whether throwing exception from current Maven plugin when meeting any error. * If set to true, the exception from current Maven plugin will fail the current Maven run. * * @since 0.1.0 */ @Parameter(property = "failsOnError", defaultValue = "true") protected boolean failsOnError; /** * Use a HTTP proxy host for the Azure Auth Client */ @Parameter(property = "httpProxyHost", readonly = false, required = false) protected String httpProxyHost; /** * Use a HTTP proxy port for the Azure Auth Client */ @Parameter(property = "httpProxyPort", defaultValue = "80") protected int httpProxyPort; private AzureAuthHelper azureAuthHelper = new AzureAuthHelper(this); private Azure azure; private TelemetryProxy telemetryProxy; private String sessionId = UUID.randomUUID().toString(); private String installationId = GetHashMac.getHashMac(); //endregion //region Getter public MavenProject getProject() { return project; } public MavenSession getSession() { return session; } public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } public Settings getSettings() { return settings; } public AuthenticationSetting getAuthenticationSetting() { return authentication; } public String getSubscriptionId() { return subscriptionId; } public boolean isTelemetryAllowed() { return allowTelemetry; } public boolean isFailingOnError() { return failsOnError; } public String getSessionId() { return sessionId; } public String getInstallationId() { return installationId == null ? "" : installationId; } public String getPluginName() { return plugin.getArtifactId(); } public String getPluginVersion() { return plugin.getVersion(); } public String getUserAgent() { return isTelemetryAllowed() ? String.format("%s/%s %s:%s %s:%s", getPluginName(), getPluginVersion(), INSTALLATION_ID_KEY, getInstallationId(), SESSION_ID_KEY, getSessionId()) : String.format("%s/%s", getPluginName(), getPluginVersion()); } public String getHttpProxyHost() { return httpProxyHost; } public int getHttpProxyPort() { return httpProxyPort; } public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { azure = azureAuthHelper.getAzureClient(); if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } else { // Repopulate subscriptionId in case it is not configured. getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } } return azure; } public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } protected void initTelemetry() { telemetryProxy = new AppInsightsProxy(this); if (!isTelemetryAllowed()) { telemetryProxy.trackEvent(TELEMETRY_NOT_ALLOWED); telemetryProxy.disable(); } } //endregion //region Telemetry Configuration Interface public Map getTelemetryProperties() { final Map map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); map.put(AUTH_TYPE, getAuthType()); return map; } // TODO: // Add AuthType ENUM and move to AzureAuthHelper. public String getAuthType() { final AuthenticationSetting authSetting = getAuthenticationSetting(); if (authSetting == null) { return "AzureCLI"; } if (StringUtils.isNotEmpty(authSetting.getServerId())) { return "ServerId"; } if (authSetting.getFile() != null) { return "AuthFile"; } return "Unknown"; } //endregion //region Entry Point @Override public void execute() throws MojoExecutionException { try { // Work around for Application Insights Java SDK: // Sometimes, NoClassDefFoundError will be thrown even after Maven build is completed successfully. // An issue has been filed at https://github.com/Microsoft/ApplicationInsights-Java/issues/416 // Before this issue is fixed, set default uncaught exception handler for all threads as work around. Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { // When maven goal executes too quick, The HTTPClient of AI SDK may not fully initialized and will step // into endless loop when close, we need to call it in main thread. // Refer here for detail codes: https://github.com/Microsoft/ApplicationInsights-Java/blob/master/core/src // /main/java/com/microsoft/applicationinsights/internal/channel/common/ApacheSender43.java#L103 ApacheSenderFactory.INSTANCE.create().close(); } } /** * Sub-class can override this method to decide whether skip execution. * * @return Boolean to indicate whether skip execution. */ protected boolean isSkipMojo() { return false; } /** * Entry point of sub-class. Sub-class should implement this method to do real work. * * @throws Exception */ protected abstract void doExecute() throws Exception; //endregion //region Telemetry protected void trackMojoSkip() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".skip"); } protected void trackMojoStart() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".start"); } protected void trackMojoSuccess() { getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".success"); } protected void trackMojoFailure(final String message) { final HashMap failureReason = new HashMap<>(); failureReason.put(FAILURE_REASON, message); getTelemetryProxy().trackEvent(this.getClass().getSimpleName() + ".failure", failureReason); } //endregion //region Helper methods protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { error(message); } } private boolean isFirstRun(Properties prop) { try { final File configurationFile = new File(CONFIGURATION_PATH); if (configurationFile.exists()) { try (InputStream input = new FileInputStream(CONFIGURATION_PATH)) { prop.load(input); final String firstRunValue = prop.getProperty(FIRST_RUN_KEY); if (firstRunValue != null && !firstRunValue.isEmpty() && firstRunValue.equalsIgnoreCase("false")) { return false; } } } else { configurationFile.getParentFile().mkdirs(); configurationFile.createNewFile(); } } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } return true; } private void updateConfigurationFile(Properties prop) { try (OutputStream output = new FileOutputStream(CONFIGURATION_PATH)) { prop.setProperty(FIRST_RUN_KEY, "false"); prop.store(output, "Azure Maven Plugin configurations"); } catch (Exception e) { // catch exceptions here to avoid blocking mojo execution. debug(e.getMessage()); } } protected class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { debug("uncaughtException: " + e); } } //endregion //region Logging public void debug(final String message) { getLog().debug(message); } public void info(final String message) { getLog().info(message); } public void infoWithMultipleLines(final String messages) { final String[] messageArray = messages.split("\\n"); for (final String line : messageArray) { getLog().info(line); } } public void warning(final String message) { getLog().warn(message); } public void error(final String message) { getLog().error(message); } //endregion } |
data class | 1 Long Method, 2 Blob, 3 Data Class, 4 Feature Envy | t | f | t | 1. Long Method, 2. Blob, 4. Feature Envy | 0 | 10932 | https://github.com/Microsoft/azure-maven-plugins/blob/d3e0b6fa0e00f38c04b622589a939fb3bae2227e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/AbstractAzureMojo.java/#L45-L447 | 1 | 1422 | 10932 | minor | |
| 486 | { "message": "YES I found bad smells", "bad smells are:": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 486 | 4755 | minor | |
| 1754 | YES I found bad smells the bad smells are: 1. Data class 2. Repeated code for getters and setters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | Data class2 Repeated code for getters and setters | t | f | t | 0 | 11867 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 2 | 1754 | 11867 | minor | ||
| 1826 | YES I found bad smells the bad smells are: 1.Long method 2.Magic number 3.Duplicate code 4.Message chains 5.Data class 6.Inappropriate intimacy 7.Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method 2Magic number 3Duplicate code 4Message chains 5Data class 6Inappropriate intimacy7Shotgun surgery | t | f | t | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 1826 | 12112 | minor | ||
| 2342 | YES I found bad smells. The bad smells are:Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14179 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 2342 | 14179 | major | |
| 1249 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | data class | t | t | t | 0 | 10434 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 1249 | 10434 | major | ||
| 1169 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Long method2 Magic numbers3 Feature envy | t | f | t | 0 | 10192 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1169 | 10192 | major | ||
| 4311 | {"response": "YES I found bad smells the bad smells are: 1. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
blob | 1. blob | t | t | t | 0 | 11363 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 4311 | 11363 | minor | ||
| 1768 | "YES I found bad smells Bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Long parameter list 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Repeated code3 Feature envy4 Long parameter list5 Primitive obsession | t | f | t | 0 | 11914 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1768 | 11914 | minor | ||
| 783 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7493 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 783 | 7493 | minor | ||
| 471 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Switch statement 5. Magic numbers (e.g. 0, 1, 2) 6. Unused variable (_s) 7. Duplicate code within cases 8. Failed state tracking 9. Indentation issues 10. Unclear variable names and method names 11. Multiple return statements within cases | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Repeated code3 Feature envy4 Switch statement5 Magic numbers (eg 0, | t | f | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 471 | 4568 | major | ||
| 2118 | YES I found bad smells the bad smells are: 1. Short method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void setOp(int opPos, int value) { m_opMap.setElementAt(value,opPos); } |
feature envy | Short method2 Feature envy | t | f | t | 0 | 13199 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xpath/compiler/OpMap.java/#L185-L188 | 2 | 2118 | 13199 | major | ||
| 1313 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10683 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 2 | 1313 | 10683 | critical | ||
| 883 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 883 | 8029 | minor | ||
| 388 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 3945 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 388 | 3945 | major | |
| 496 | {"output": "YES I found bad smells\nthe bad smells are: Blob, Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DiscoverAnnotatedBeans implements DynamicDeployer { public AppModule deploy(AppModule appModule) throws OpenEJBException { for (EjbModule ejbModule : appModule.getEjbModules()) { ejbModule.initAppModule(appModule); setModule(ejbModule); try { deploy(ejbModule); } finally { removeModule(); } } for (ClientModule clientModule : appModule.getClientModules()) { clientModule.initAppModule(appModule); setModule(clientModule); try { deploy(clientModule); } finally { removeModule(); } } for (ConnectorModule connectorModule : appModule.getConnectorModules()) { connectorModule.initAppModule(appModule); setModule(connectorModule); try { deploy(connectorModule); } finally { removeModule(); } } for (WebModule webModule : appModule.getWebModules()) { webModule.initAppModule(appModule); setModule(webModule); try { deploy(webModule); } finally { removeModule(); } } final AdditionalBeanDiscoverer discoverer = SystemInstance.get().getComponent(AdditionalBeanDiscoverer.class); if (discoverer != null) { appModule = discoverer.discover(appModule); } return appModule; } public ClientModule deploy(ClientModule clientModule) throws OpenEJBException { if (clientModule.getApplicationClient() == null){ clientModule.setApplicationClient(new ApplicationClient()); } // Lots of jars have main classes so this might not even be an app client. // We're not going to scrape it for @LocalClient or @RemoteClient annotations // unless they flag us specifically by adding a META-INF/application-client.xml // // ClientModules that already have a AnnotationFinder have been generated automatically // from an EjbModule, so we don't skip those ever. if (clientModule.getFinder() == null && clientModule.getAltDDs().containsKey("application-client.xml")) if (clientModule.getApplicationClient() != null && clientModule.getApplicationClient().isMetadataComplete()) return clientModule; IAnnotationFinder finder = clientModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(clientModule); } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForClientModule.url", clientModule.getJarLocation()); return clientModule; } catch (Exception e) { startupLogger.warning("startup.scrapeFailedForClientModule", e, clientModule.getJarLocation()); return clientModule; } } // This method is also called by the deploy(EjbModule) method to see if those // modules have any @LocalClient or @RemoteClient classes for (Annotated> clazz : finder.findMetaAnnotatedClasses(LocalClient.class)) { clientModule.getLocalClients().add(clazz.get().getName()); } for (Annotated> clazz : finder.findMetaAnnotatedClasses(RemoteClient.class)) { clientModule.getRemoteClients().add(clazz.get().getName()); } if (clientModule.getApplicationClient() == null){ if (clientModule.getRemoteClients().size() > 0 || clientModule.getLocalClients().size() > 0) { clientModule.setApplicationClient(new ApplicationClient()); } } return clientModule; } public ConnectorModule deploy(ConnectorModule connectorModule) throws OpenEJBException { org.apache.openejb.jee.Connector connector = connectorModule.getConnector(); if (connector == null) { connector = new org.apache.openejb.jee.Connector(); } // JCA 1.6 - 18.3.1 do not look at annotations if the provided connector // deployment descriptor is "meta-data complete". float specVersion = 0; try { specVersion = Float.parseFloat(connector.getVersion()); } catch (Exception e) { } if (specVersion < 1.6 || Boolean.TRUE.equals(connector.isMetadataComplete())) { return connectorModule; } IAnnotationFinder finder = connectorModule.getFinder(); if (finder == null) { try { finder = FinderFactory.createFinder(connectorModule); connectorModule.setFinder(finder); } catch (Exception e) { // TODO: some sort of error return connectorModule; } } List> connectorClasses = finder.findAnnotatedClasses(Connector.class); // are we allowed to have more than one connector class? Not without a deployment descriptor if (connector.getResourceAdapter() == null || connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { if (connectorClasses.size() == 0) { // fail some validation here too } if (connectorClasses.size() > 1) { // too many connector classes, this is against the spec // something like connectorModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); } } Class connectorClass = null; if (connectorClasses.size() == 1) { connectorClass = connectorClasses.get(0); } if (connectorClasses.size() > 1) { for (Class cls : connectorClasses) { if (cls.getName().equals(connector.getResourceAdapter().getResourceAdapterClass())) { connectorClass = cls; break; } } } if (connectorClass != null) { if (connector.getResourceAdapter() == null) { connector.setResourceAdapter(new ResourceAdapter()); } if (connector.getResourceAdapter().getResourceAdapterClass() == null || connector.getResourceAdapter().getResourceAdapterClass().length() == 0) { connector.getResourceAdapter().setResourceAdapterClass(connectorClass.getName()); } Connector connectorAnnotation = connectorClass.getAnnotation(Connector.class); connector.setDisplayNames(getTexts(connector.getDisplayNames(), connectorAnnotation.displayName())); connector.setDescriptions(getTexts(connector.getDescriptions(), connectorAnnotation.description())); connector.setEisType(getString(connector.getEisType(), connectorAnnotation.eisType())); connector.setVendorName(getString(connector.getVendorName(), connectorAnnotation.vendorName())); connector.setResourceAdapterVersion(getString(connector.getResourceAdapterVersion(), connectorAnnotation.version())); if (connector.getIcons().isEmpty()) { int smallIcons = connectorAnnotation.smallIcon().length; int largeIcons = connectorAnnotation.largeIcon().length; for (int i = 0; i < smallIcons && i < largeIcons; i++) { Icon icon = new Icon(); // locale can't be specified in the annotation and it is en by default // so on other systems it doesn't work because Icon return the default locale icon.setLang(Locale.getDefault().getLanguage()); if (i < smallIcons) { icon.setSmallIcon(connectorAnnotation.smallIcon()[i]); } if (i < largeIcons) { icon.setLargeIcon(connectorAnnotation.largeIcon()[i]); } connector.getIcons().add(icon); } } if (connector.getLicense() == null) { License license = new License(); connector.setLicense(license); license.setLicenseRequired(connectorAnnotation.licenseRequired()); } connector.getLicense().setDescriptions(getTexts(connector.getLicense().getDescriptions(), connectorAnnotation.licenseDescription())); SecurityPermission[] annotationSecurityPermissions = connectorAnnotation.securityPermissions(); List securityPermission = connector.getResourceAdapter().getSecurityPermission(); if (securityPermission == null || securityPermission.size() == 0) { for (SecurityPermission sp : annotationSecurityPermissions) { org.apache.openejb.jee.SecurityPermission permission = new org.apache.openejb.jee.SecurityPermission(); permission.setSecurityPermissionSpec(sp.permissionSpec()); permission.setDescriptions(stringsToTexts(sp.description())); securityPermission.add(permission); } } Class[] annotationRequiredWorkContexts = connectorAnnotation.requiredWorkContexts(); List requiredWorkContext = connector.getRequiredWorkContext(); if (requiredWorkContext.size() == 0) { for (Class cls : annotationRequiredWorkContexts) { requiredWorkContext.add(cls.getName()); } } OutboundResourceAdapter outboundResourceAdapter = connector.getResourceAdapter().getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); connector.getResourceAdapter().setOutboundResourceAdapter(outboundResourceAdapter); } List authenticationMechanisms = outboundResourceAdapter.getAuthenticationMechanism(); javax.resource.spi.AuthenticationMechanism[] authMechanisms = connectorAnnotation.authMechanisms(); if (authenticationMechanisms.size() == 0) { for (javax.resource.spi.AuthenticationMechanism am : authMechanisms) { AuthenticationMechanism authMechanism = new AuthenticationMechanism(); authMechanism.setAuthenticationMechanismType(am.authMechanism()); authMechanism.setCredentialInterface(am.credentialInterface().toString()); authMechanism.setDescriptions(stringsToTexts(am.description())); authenticationMechanisms.add(authMechanism); } } if (outboundResourceAdapter.getTransactionSupport() == null) { outboundResourceAdapter.setTransactionSupport(TransactionSupportType.fromValue(connectorAnnotation.transactionSupport().toString())); } if (outboundResourceAdapter.isReauthenticationSupport() == null) { outboundResourceAdapter.setReauthenticationSupport(connectorAnnotation.reauthenticationSupport()); } } else { // we couldn't process a connector class - probably a validation issue which we should warn about. } // process @ConnectionDescription(s) List> classes = finder.findAnnotatedClasses(ConnectionDefinitions.class); for (Class cls : classes) { ConnectionDefinitions connectionDefinitionsAnnotation = cls.getAnnotation(ConnectionDefinitions.class); ConnectionDefinition[] definitions = connectionDefinitionsAnnotation.value(); for (ConnectionDefinition definition : definitions) { processConnectionDescription(connector.getResourceAdapter(), definition, cls); } } classes = finder.findAnnotatedClasses(ConnectionDefinition.class); for (Class cls : classes) { ConnectionDefinition connectionDefinitionAnnotation = cls.getAnnotation(ConnectionDefinition.class); processConnectionDescription(connector.getResourceAdapter(), connectionDefinitionAnnotation, cls); } InboundResourceadapter inboundResourceAdapter = connector.getResourceAdapter().getInboundResourceAdapter(); if (inboundResourceAdapter == null) { inboundResourceAdapter = new InboundResourceadapter(); connector.getResourceAdapter().setInboundResourceAdapter(inboundResourceAdapter); } MessageAdapter messageAdapter = inboundResourceAdapter.getMessageAdapter(); if (messageAdapter == null) { messageAdapter = new MessageAdapter(); inboundResourceAdapter.setMessageAdapter(messageAdapter); } classes = finder.findAnnotatedClasses(Activation.class); for (Class cls : classes) { MessageListener messageListener = null; Activation activationAnnotation = cls.getAnnotation(Activation.class); List messageListeners = messageAdapter.getMessageListener(); for (MessageListener ml : messageListeners) { if (cls.getName().equals(ml.getActivationSpec().getActivationSpecClass())) { messageListener = ml; break; } } if (messageListener == null) { Class[] listeners = activationAnnotation.messageListeners(); for (Class listener : listeners) { messageAdapter.addMessageListener(new MessageListener(listener.getName(), cls.getName())); } } } classes = finder.findAnnotatedClasses(AdministeredObject.class); List adminObjects = connector.getResourceAdapter().getAdminObject(); for (Class cls : classes) { AdministeredObject administeredObjectAnnotation = cls.getAnnotation(AdministeredObject.class); Class[] adminObjectInterfaces = administeredObjectAnnotation.adminObjectInterfaces(); AdminObject adminObject = null; for (AdminObject admObj : adminObjects) { if (admObj.getAdminObjectClass().equals(cls.getName())) { adminObject = admObj; } } if (adminObject == null) { for (Class iface : adminObjectInterfaces) { AdminObject newAdminObject = new AdminObject(); newAdminObject.setAdminObjectClass(cls.getName()); newAdminObject.setAdminObjectInterface(iface.getName()); adminObjects.add(newAdminObject); } } } // need to make a list of classes to process for config properties // resource adapter String raCls = connector.getResourceAdapter().getResourceAdapterClass(); process(connectorModule.getClassLoader(), raCls, connector.getResourceAdapter()); // managedconnectionfactory if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getOutboundResourceAdapter() != null) { List connectionDefinitions = connector.getResourceAdapter().getOutboundResourceAdapter().getConnectionDefinition(); for (org.apache.openejb.jee.ConnectionDefinition connectionDefinition : connectionDefinitions) { process(connectorModule.getClassLoader(), connectionDefinition.getManagedConnectionFactoryClass(), connectionDefinition); } } // administeredobject if (connector.getResourceAdapter() != null) { List raAdminObjects = connector.getResourceAdapter().getAdminObject(); for (AdminObject raAdminObject : raAdminObjects) { process(connectorModule.getClassLoader(), raAdminObject.getAdminObjectClass(), raAdminObject); } } // activationspec if (connector.getResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter() != null && connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter() != null) { List messageListeners = connector.getResourceAdapter().getInboundResourceAdapter().getMessageAdapter().getMessageListener(); for (MessageListener messageListener : messageListeners) { ActivationSpec activationSpec = messageListener.getActivationSpec(); process(connectorModule.getClassLoader(), activationSpec.getActivationSpecClass(), activationSpec); } } return connectorModule; } void process(ClassLoader cl, String cls, Object object) { List configProperties = null; try { // grab a list of ConfigProperty objects configProperties = (List) object.getClass().getDeclaredMethod("getConfigProperty").invoke(object); } catch (Exception e) { } if (configProperties == null) { // can't get config properties return; } ClassLoader classLoader = cl; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } final List allowedTypes = Arrays.asList(new String[] { Boolean.class.getName(), String.class.getName(), Integer.class.getName(), Double.class.getName(), Byte.class.getName(), Short.class.getName(), Long.class.getName(), Float.class.getName(), Character.class.getName()}); try { Class clazz = classLoader.loadClass(realClassName(cls)); Object o = clazz.newInstance(); // add any introspected properties BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String name = propertyDescriptor.getName(); Class type = propertyDescriptor.getPropertyType(); if (type == null) { continue; } if (type.isPrimitive()) { type = getWrapper(type.getName()); } if (! allowedTypes.contains(type.getName())) { continue; } if (! containsConfigProperty(configProperties, name)) { if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); Object value = null; try { value = propertyDescriptor.getReadMethod().invoke(o); } catch (Exception e) { } javax.resource.spi.ConfigProperty annotation = propertyDescriptor.getWriteMethod().getAnnotation(javax.resource.spi.ConfigProperty.class); if (annotation == null) { try { // if there's no annotation on the setter, we'll try and scrape one off the field itself (assuming the same name) annotation = clazz.getDeclaredField(name).getAnnotation(javax.resource.spi.ConfigProperty.class); } catch (Exception ignored) { // no-op : getDeclaredField() throws exceptions and does not return null } } configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(getConfigPropertyType(annotation, type)); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null && annotation.defaultValue().length() > 0) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); configProperty.setDescriptions(stringsToTexts(annotation.description())); } } } } // add any annotated fields we haven't already picked up Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { javax.resource.spi.ConfigProperty annotation = field.getAnnotation(javax.resource.spi.ConfigProperty.class); String name = field.getName(); Object value = null; try { value = field.get(o); } catch (Exception e) { } if (! containsConfigProperty(configProperties, name)) { String type = getConfigPropertyType(annotation, field.getType()); if (type != null) { ConfigProperty configProperty = new ConfigProperty(); configProperties.add(configProperty); configProperty.setConfigPropertyName(name); configProperty.setConfigPropertyType(type); if (value != null) { configProperty.setConfigPropertyValue(value.toString()); } if (annotation != null) { if (annotation.defaultValue() != null) { configProperty.setConfigPropertyValue(annotation.defaultValue()); } configProperty.setConfigPropertyConfidential(annotation.confidential()); configProperty.setConfigPropertyIgnore(annotation.ignore()); configProperty.setConfigPropertySupportsDynamicUpdates(annotation.supportsDynamicUpdates()); } } } } } catch (Exception e) { e.printStackTrace(); } } private String getConfigPropertyType(javax.resource.spi.ConfigProperty annotation, Class type) { Class t = (annotation == null) ? null : annotation.type(); if (t == null && type != null) { return type.getName(); } else if (t == null) { return null; } if (t.equals(Object.class)) { t = type; } if (t == null) { // t == null && type == null return null; } if (t.isPrimitive()) { t = getWrapper(t.getName()); } return t.getName(); } private boolean containsConfigProperty(List configProperties, String name) { for (ConfigProperty configProperty : configProperties) { if (configProperty.getConfigPropertyName().equals(name)) { return true; } } return false; } private Class getWrapper(String primitiveType) { final Map> builtInMap = new HashMap>();{ builtInMap.put("int", Integer.class); builtInMap.put("long", Long.class); builtInMap.put("double", Double.class); builtInMap.put("float", Float.class); builtInMap.put("boolean", Boolean.class); builtInMap.put("char", Character.class); builtInMap.put("byte", Byte.class); builtInMap.put("void", Void.class); builtInMap.put("short", Short.class); } return builtInMap.get(primitiveType); } private void processConnectionDescription(ResourceAdapter resourceAdapter, ConnectionDefinition connectionDefinitionAnnotation, Class cls) { // try and find the managed connection factory OutboundResourceAdapter outboundResourceAdapter = resourceAdapter.getOutboundResourceAdapter(); if (outboundResourceAdapter == null) { outboundResourceAdapter = new OutboundResourceAdapter(); resourceAdapter.setOutboundResourceAdapter(outboundResourceAdapter); } List connectionDefinition = outboundResourceAdapter.getConnectionDefinition(); org.apache.openejb.jee.ConnectionDefinition definition = null; for (org.apache.openejb.jee.ConnectionDefinition cd : connectionDefinition) { if (cd.getManagedConnectionFactoryClass().equals(cls.getName())) { definition = cd; break; } } if (definition == null) { definition = new org.apache.openejb.jee.ConnectionDefinition(); outboundResourceAdapter.getConnectionDefinition().add(definition); } if (definition.getManagedConnectionFactoryClass() == null) { definition.setManagedConnectionFactoryClass(cls.getName()); } if (definition.getConnectionInterface() == null) { definition.setConnectionInterface(connectionDefinitionAnnotation.connection().getName()); } if (definition.getConnectionImplClass() == null) { definition.setConnectionImplClass(connectionDefinitionAnnotation.connectionImpl().getName()); } if (definition.getConnectionFactoryInterface() == null) { definition.setConnectionFactoryInterface(connectionDefinitionAnnotation.connectionFactory().getName()); } if (definition.getConnectionFactoryImplClass() == null) { definition.setConnectionFactoryImplClass(connectionDefinitionAnnotation.connectionFactoryImpl().getName()); } } private Text[] stringsToTexts(String[] strings) { if (strings == null) { return null; } Text[] result = new Text[strings.length]; for (int i = 0; i < result.length; i++) { result[i] = new Text(); result[i].setValue(strings[i]); } return result; } private String getString(String descriptorString, String annotationString) { if (descriptorString != null && descriptorString.length() > 0) { return descriptorString; } if (annotationString != null && annotationString.length() > 0) { return annotationString; } return null; } private Text[] getTexts(Text[] originalTexts, String[] newStrings) { if (newStrings != null && newStrings.length > 0 && (originalTexts == null || originalTexts.length == 0)) { Text[] texts = new Text[newStrings.length]; for (int i = 0; i < newStrings.length; i++) { texts[i] = new Text(null, newStrings[i]); } return texts; } else { return originalTexts; } } public WebModule deploy(WebModule webModule) throws OpenEJBException { WebApp webApp = webModule.getWebApp(); if (webApp != null && (webApp.isMetadataComplete())) return webModule; try { if (webModule.getFinder() == null) { webModule.setFinder(FinderFactory.createFinder(webModule)); } } catch (Exception e) { startupLogger.warning("Unable to scrape for @WebService or @WebServiceProvider annotations. AnnotationFinder failed.", e); return webModule; } if (webApp == null) { webApp = new WebApp(); webModule.setWebApp(webApp); } List existingServlets = new ArrayList(); for (Servlet servlet : webApp.getServlet()) { if (servlet.getServletClass() != null) { existingServlets.add(servlet.getServletClass()); } } IAnnotationFinder finder = webModule.getFinder(); List classes = new ArrayList(); classes.addAll(finder.findAnnotatedClasses(WebService.class)); classes.addAll(finder.findAnnotatedClasses(WebServiceProvider.class)); for (Class webServiceClass : classes) { // If this class is also annotated @Stateless or @Singleton, we should skip it if (webServiceClass.isAnnotationPresent(Singleton.class) || webServiceClass.isAnnotationPresent(Stateless.class)) { webModule.getEjbWebServices().add(webServiceClass.getName()); continue; } int modifiers = webServiceClass.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers) || isAbstract(modifiers)) { continue; } if (existingServlets.contains(webServiceClass.getName())) continue; // create webApp and webservices objects if they don't exist already // add new element Servlet servlet = new Servlet(); servlet.setServletName(webServiceClass.getName()); servlet.setServletClass(webServiceClass.getName()); webApp.getServlet().add(servlet); } /* * REST */ // get by annotations webModule.getRestClasses().addAll(findRestClasses(webModule, finder)); addJaxRsProviders(finder, webModule.getJaxrsProviders(), Provider.class); // Applications with a default constructor // findSubclasses will not work by default to gain a lot of time // look FinderFactory for the flag to activate it or // use @ApplicationPath("/") List> applications = finder.findSubclasses(Application.class); for (Class app : applications) { addRestApplicationIfPossible(webModule, app); } // look for ApplicationPath, it will often return the same than the previous one // but without finder.link() invocation it still works // so it can save a lot of startup time List>> applicationsByAnnotation = finder.findMetaAnnotatedClasses(ApplicationPath.class); for (Annotated> annotatedApp : applicationsByAnnotation) { final Class app = annotatedApp.get(); if (!Application.class.isAssignableFrom(app)) { logger.error("class '" + app.getName() + "' is annotated with @ApplicationPath but doesn't implement " + Application.class.getName()); continue; } addRestApplicationIfPossible(webModule, (Class) app); } /* * JSF */ final ClassLoader classLoader = webModule.getClassLoader(); for (String jsfClass : JSF_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(jsfClass); } catch (ClassNotFoundException e) { continue; } final List>> found = finder.findMetaAnnotatedClasses(clazz); final Set convertedClasses = new HashSet(found.size()); for (Annotated> annotated : found) { convertedClasses.add(annotated.get().getName()); } webModule.getJsfAnnotatedClasses().put(jsfClass, convertedClasses); } /* * Servlet, Filter, Listener */ Map urlByClasses = null; for (String apiClassName : WEB_CLASSES) { final Class clazz; try { clazz = (Class) classLoader.loadClass(apiClassName); } catch (ClassNotFoundException e) { continue; } if (urlByClasses == null) { // try to reuse scanning info, maybe some better indexing can be a nice idea if (finder instanceof FinderFactory.ModuleLimitedFinder) { final IAnnotationFinder limitedFinder = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (limitedFinder instanceof AnnotationFinder) { final Archive archive = ((AnnotationFinder) limitedFinder).getArchive(); if (archive instanceof WebappAggregatedArchive) { final Map> index = ((WebappAggregatedArchive) archive).getClassesMap(); urlByClasses = new HashMap(); for (Map.Entry> entry : index.entrySet()) { final String url = entry.getKey().toExternalForm(); for (String current : entry.getValue()) { urlByClasses.put(current, url); } } } } } } final List>> found = finder.findMetaAnnotatedClasses(clazz); addWebAnnotatedClassInfo(urlByClasses, webModule.getWebAnnotatedClasses(), found); } if (urlByClasses != null) { urlByClasses.clear(); } return webModule; } private void addJaxRsProviders(final IAnnotationFinder finder, final Collection set, final Class annotation) { for (Annotated> provider : finder.findMetaAnnotatedClasses(annotation)) { set.add(provider.get().getName()); } } private static void addRestApplicationIfPossible(final WebModule webModule, final Class app) { if (app.getConstructors().length == 0) { webModule.getRestApplications().add(app.getName()); } else { for (Constructor ctr : app.getConstructors()) { if (ctr.getParameterTypes().length == 0) { webModule.getRestApplications().add(app.getName()); break; } } } } public EjbModule deploy(EjbModule ejbModule) throws OpenEJBException { if (ejbModule.getEjbJar() != null && ejbModule.getEjbJar().isMetadataComplete()) return ejbModule; try { if (ejbModule.getFinder() == null) { ejbModule.setFinder(FinderFactory.createFinder(ejbModule)); } } catch (MalformedURLException e) { startupLogger.warning("startup.scrapeFailedForModule", ejbModule.getJarLocation()); return ejbModule; } catch (Exception e) { startupLogger.warning("Unable to scrape for @Stateful, @Stateless, @Singleton or @MessageDriven annotations. AnnotationFinder failed.", e); return ejbModule; } IAnnotationFinder finder = ejbModule.getFinder(); final List managedClasses; { final Beans beans = ejbModule.getBeans(); if (beans != null) { managedClasses = beans.getManagedClasses(); final List classNames = getBeanClasses(finder); for (String rawClassName : classNames) { final String className = realClassName(rawClassName); try { final ClassLoader loader = ejbModule.getClassLoader(); final Class clazz = loader.loadClass(className); // The following can NOT be beans in CDI // 1. Non-static inner classes if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) continue; // // // 2. Abstract classes (unless they are an @Decorator) // if (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isAnnotationPresent(javax.decorator.Decorator.class)) continue; // // 3. Implementations of Extension if (Extension.class.isAssignableFrom(clazz)) continue; managedClasses.add(className); } catch (ClassNotFoundException e) { // todo log debug warning } catch (java.lang.NoClassDefFoundError e) { // no-op } } // passing jar location to be able to manage maven classes/test-classes which have the same moduleId String id = ejbModule.getModuleId(); if (ejbModule.getJarLocation() != null && ejbModule.getJarLocation().contains(ejbModule.getModuleId() + "/target/test-classes".replace("/", File.separator))) { // with maven if both src/main/java and src/test/java are deployed // moduleId.Comp exists twice so it fails // here we simply modify the test comp bean name to avoid it id += "_test"; } final String name = BeanContext.Comp.openejbCompName(id); final org.apache.openejb.jee.ManagedBean managedBean = new CompManagedBean(name, BeanContext.Comp.class); managedBean.setTransactionType(TransactionType.BEAN); ejbModule.getEjbJar().addEnterpriseBean(managedBean); } else { managedClasses = new ArrayList(); } } final Set> specializingClasses = new HashSet>(); // Fill in default sessionType for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (!(bean instanceof SessionBean)) continue; SessionBean sessionBean = (SessionBean) bean; if (sessionBean.getSessionType() != null) continue; try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); sessionBean.setSessionType(getSessionType(clazz)); } catch (Throwable handledInValidation) { // no-op } } // Fill in default ejbName for xml declared EJBs for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) { if (bean.getEjbClass() == null) continue; if (bean.getEjbName() == null || bean.getEjbName().startsWith("@NULL@")) { ejbModule.getEjbJar().removeEnterpriseBean(bean.getEjbName()); try { final Class clazz = ejbModule.getClassLoader().loadClass(bean.getEjbClass()); final String ejbName = getEjbName(bean, clazz); bean.setEjbName(ejbName); } catch (Throwable handledInValidation) { } ejbModule.getEjbJar().addEnterpriseBean(bean); } } /* 19.2: ejb-name: Default is the unqualified name of the bean class */ EjbJar ejbJar = ejbModule.getEjbJar(); for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Singleton.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Singleton singleton = beanClass.getAnnotation(Singleton.class); String ejbName = getEjbName(singleton, beanClass.get()); if (!isValidEjbAnnotationUsage(Singleton.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new SingletonBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.SINGLETON); if (singleton.mappedName() != null) { sessionBean.setMappedName(singleton.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateless.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateless stateless = beanClass.getAnnotation(Stateless.class); String ejbName = getEjbName(stateless, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateless.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatelessBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.STATELESS); if (stateless.mappedName() != null) { sessionBean.setMappedName(stateless.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } // The Specialization code is good, but it possibly needs to be moved to after the full processing of the bean // the plus is that it would get the required interfaces. The minus is that it would get all the other items // Possibly study alternatives. Alternatives might have different meta data completely while it seems Specializing beans inherit all meta-data // Anyway.. the qualifiers aren't getting inherited, so we need to fix that for (Annotated> beanClass : finder.findMetaAnnotatedClasses(Stateful.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } Stateful stateful = beanClass.getAnnotation(Stateful.class); String ejbName = getEjbName(stateful, beanClass.get()); if (!isValidEjbAnnotationUsage(Stateful.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new StatefulBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; // TODO: We might be stepping on an xml override here sessionBean.setSessionType(SessionType.STATEFUL); if (stateful.mappedName() != null) { sessionBean.setMappedName(stateful.mappedName()); } } LegacyProcessor.process(beanClass.get(), enterpriseBean); } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(ManagedBean.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } ManagedBean managed = beanClass.getAnnotation(ManagedBean.class); String ejbName = getEjbName(managed, beanClass.get()); // TODO: this is actually against the spec, but the requirement is rather silly // (allowing @Stateful and @ManagedBean on the same class) // If the TCK doesn't complain we should discourage it if (!isValidEjbAnnotationUsage(ManagedBean.class, beanClass, ejbName, ejbModule)) continue; EnterpriseBean enterpriseBean = ejbJar.getEnterpriseBean(ejbName); if (enterpriseBean == null) { enterpriseBean = new org.apache.openejb.jee.ManagedBean(ejbName, beanClass.get()); ejbJar.addEnterpriseBean(enterpriseBean); } if (enterpriseBean.getEjbClass() == null) { enterpriseBean.setEjbClass(beanClass.get()); } if (enterpriseBean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) enterpriseBean; sessionBean.setSessionType(SessionType.MANAGED); final TransactionType transactionType = sessionBean.getTransactionType(); if (transactionType == null) sessionBean.setTransactionType(TransactionType.BEAN); } } for (Annotated> beanClass : finder.findMetaAnnotatedClasses(MessageDriven.class)) { if (beanClass.isAnnotationPresent(Specializes.class)) { managedClasses.remove(beanClass.get().getName()); specializingClasses.add(beanClass.get()); continue; } MessageDriven mdb = beanClass.getAnnotation(MessageDriven.class); String ejbName = getEjbName(mdb, beanClass.get()); if (!isValidEjbAnnotationUsage(MessageDriven.class, beanClass, ejbName, ejbModule)) continue; MessageDrivenBean messageBean = (MessageDrivenBean) ejbJar.getEnterpriseBean(ejbName); if (messageBean == null) { messageBean = new MessageDrivenBean(ejbName); ejbJar.addEnterpriseBean(messageBean); } if (messageBean.getEjbClass() == null) { messageBean.setEjbClass(beanClass.get()); } LegacyProcessor.process(beanClass.get(), messageBean); } for (Class specializingClass : sortClassesParentFirst(new ArrayList>(specializingClasses))) { final Class parent = specializingClass.getSuperclass(); if (parent == null || parent.equals(Object.class)) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsNothing", specializingClass.getName()); } boolean found = false; for (EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) { final String ejbClass = enterpriseBean.getEjbClass(); if (ejbClass != null && ejbClass.equals(parent.getName())) { managedClasses.remove(ejbClass); enterpriseBean.setEjbClass(specializingClass.getName()); found = true; } } if (!found) { ejbModule.getValidation().fail(specializingClass.getSimpleName(), "specializes.extendsSimpleBean", specializingClass.getName()); } } AssemblyDescriptor assemblyDescriptor = ejbModule.getEjbJar().getAssemblyDescriptor(); if (assemblyDescriptor == null) { assemblyDescriptor = new AssemblyDescriptor(); ejbModule.getEjbJar().setAssemblyDescriptor(assemblyDescriptor); } startupLogger.debug("Searching for annotated application exceptions (see OPENEJB-980)"); List> appExceptions = finder.findAnnotatedClasses(ApplicationException.class); for (Class exceptionClass : appExceptions) { startupLogger.debug("...handling " + exceptionClass); ApplicationException annotation = exceptionClass.getAnnotation(ApplicationException.class); if (assemblyDescriptor.getApplicationException(exceptionClass) == null) { startupLogger.debug("...adding " + exceptionClass + " with rollback=" + annotation.rollback()); assemblyDescriptor.addApplicationException(exceptionClass, annotation.rollback(), annotation.inherited()); } else { mergeApplicationExceptionAnnotation(assemblyDescriptor, exceptionClass, annotation); } } // ejb can be rest bean and only then in standalone so scan providers here too // adding them to app since they should be in the app classloader if (ejbModule.getAppModule() != null) { addJaxRsProviders(finder, ejbModule.getAppModule().getJaxRsProviders(), Provider.class); } if (ejbModule.getAppModule() != null) { for (PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) { for (org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) { if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses()) && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) { final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE); // no need of meta currently since JPA providers doesn't support it final List> classes = new ArrayList>(); classes.addAll(finder.findAnnotatedClasses(Entity.class)); classes.addAll(finder.findAnnotatedClasses(Embeddable.class)); classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class)); final List existingClasses = pu.getClazz(); for (Class clazz : classes) { final String name = clazz.getName(); if ((packageName == null || name.startsWith(packageName)) && !existingClasses.contains(name)) { pu.getClazz().add(name); } } pu.setScanned(true); } } } } return ejbModule; } private SessionType getSessionType(Class clazz) { if (clazz.isAnnotationPresent(Stateful.class)) return SessionType.STATEFUL; if (clazz.isAnnotationPresent(Stateless.class)) return SessionType.STATELESS; if (clazz.isAnnotationPresent(Singleton.class)) return SessionType.SINGLETON; if (clazz.isAnnotationPresent(ManagedBean.class)) return SessionType.MANAGED; return null; } private String getEjbName(EnterpriseBean bean, Class clazz) { if (bean instanceof SessionBean) { SessionBean sessionBean = (SessionBean) bean; switch (sessionBean.getSessionType()) { case STATEFUL: { final Stateful annotation = clazz.getAnnotation(Stateful.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case STATELESS: { final Stateless annotation = clazz.getAnnotation(Stateless.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } case SINGLETON: { final Singleton annotation = clazz.getAnnotation(Singleton.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } } } if (bean instanceof MessageDrivenBean) { final MessageDriven annotation = clazz.getAnnotation(MessageDriven.class); if (annotation != null && specified(annotation.name())) { return annotation.name(); } } return clazz.getSimpleName(); } private static boolean specified(final String name) { return name != null && name.length() != 0; } private List getBeanClasses(IAnnotationFinder finder) { // What we're hoping in this method is to get lucky and find // that our 'finder' instances is an AnnotationFinder that is // holding an AggregatedArchive so we can get the classes that // that pertain to each URL for CDI purposes. // // If not we call finder.getAnnotatedClassNames() which may return // more classes than actually apply to CDI. This can "pollute" // the CDI class space and break injection points if (!(finder instanceof FinderFactory.ModuleLimitedFinder)) return finder.getAnnotatedClassNames(); final IAnnotationFinder delegate = ((FinderFactory.ModuleLimitedFinder) finder).getDelegate(); if (!(delegate instanceof AnnotationFinder)) return finder.getAnnotatedClassNames(); final AnnotationFinder annotationFinder = (AnnotationFinder) delegate; final Archive archive = annotationFinder.getArchive(); if (!(archive instanceof WebappAggregatedArchive)) return finder.getAnnotatedClassNames(); final List classes = new ArrayList(); final WebappAggregatedArchive aggregatedArchive = (WebappAggregatedArchive) archive; final Map> map = aggregatedArchive.getClassesMap(); for (Map.Entry> entry : map.entrySet()) { if (hasBeansXml(entry.getKey())) classes.addAll(entry.getValue()); } return classes; } public static boolean hasBeansXml(URL url) { if (url.getPath().endsWith("WEB-INF/classes/")) return true; if (url.getPath().endsWith("!/META-INF/beans.xml")) return true; try { final URLClassLoader loader = new URLClassLoader(new URL[]{ url } , new EmptyResourcesClassLoader()); String[] paths = { "META-INF/beans.xml", "WEB-INF/beans.xml", "/WEB-INF/beans.xml", "/META-INF/beans.xml", }; for (String path : paths) { if (loader.findResource(path) != null) return true; } } catch (Exception e) { } return false; } private String getEjbName(MessageDriven mdb, Class beanClass) { return (mdb.name().isEmpty() ? beanClass.getSimpleName() : mdb.name()); } private String getEjbName(Stateful stateful, Class beanClass) { return (stateful.name().isEmpty() ? beanClass.getSimpleName() : stateful.name()); } private String getEjbName(Stateless stateless, Class beanClass) { return (stateless.name().isEmpty() ? beanClass.getSimpleName() : stateless.name()); } private String getEjbName(Singleton singleton, Class beanClass) { return (singleton.name().isEmpty() ? beanClass.getSimpleName() : singleton.name()); } private String getEjbName(ManagedBean managed, Class beanClass) { return (managed.value().isEmpty() ? beanClass.getSimpleName() : managed.value()); } private boolean isValidEjbAnnotationUsage(Class annotationClass, Annotated> beanClass, String ejbName, EjbModule ejbModule) { List> annotations = new ArrayList(asList(Singleton.class, Stateless.class, Stateful.class, MessageDriven.class)); annotations.remove(annotationClass); boolean b = true; for (Class secondAnnotation : annotations) { Annotation annotation = beanClass.getAnnotation(secondAnnotation); if (annotation == null) continue; String secondEjbName = null; if (annotation instanceof Stateful) { secondEjbName = getEjbName((Stateful) annotation, beanClass.get()); } else if (annotation instanceof Stateless) { secondEjbName = getEjbName((Stateless) annotation, beanClass.get()); } else if (annotation instanceof Singleton) { secondEjbName = getEjbName((Singleton) annotation, beanClass.get()); } else if (annotation instanceof MessageDriven) { secondEjbName = getEjbName((MessageDriven) annotation, beanClass.get()); } if (ejbName.equals(secondEjbName)) { ejbModule.getValidation().fail(ejbName, "multiplyAnnotatedAsBean", annotationClass.getSimpleName(), secondAnnotation.getSimpleName(), ejbName, beanClass.get().getName()); } } // not a dynamic proxy implemented bean if (beanClass.getAnnotation(PersistenceContext.class) == null && beanClass.getAnnotation(Proxy.class) == null && beanClass.get().isInterface()) { ejbModule.getValidation().fail(ejbName, "interfaceAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } if (!beanClass.get().isInterface() && isAbstract(beanClass.get().getModifiers())) { ejbModule.getValidation().fail(ejbName, "abstractAnnotatedAsBean", annotationClass.getSimpleName(), beanClass.get().getName()); return false; } return b; } } |
blob | blob, long method | t | t | t | long method | 0 | 5024 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/config/AnnotationDeployer.java/#L411-L1700 | 1 | 496 | 5024 | major | |
| 2551 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
feature envy | Long method2 Feature envy3 Primitive obsession | t | f | t | 0 | 14798 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 2 | 2551 | 14798 | minor | ||
| 35 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 743 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 35 | 743 | minor | |
| 756 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class, 3. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | 1. long method, 2. data class, 3. blob | t | t | t | 2. data class, 3. blob | 0 | 7049 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 1 | 756 | 7049 | minor | |
| 1102 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9840 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1102 | 9840 | minor | ||
| 1343 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | 1. long method, 2. blob | t | t | t | 2. blob | 0 | 10745 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1343 | 10745 | minor | |
| 2262 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Nested loops 6. Conditional complexity 7. Misleading variable names 8. Hard-coded strings 9. Bad indentation and formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Nested loops6 Conditional complexity7 Misleading variable names8 Hard-coded strings9 Bad indentation and formatting | t | f | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 2262 | 13720 | critical | ||
| 2655 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | data class, long method | t | t | t | long method | 0 | 15181 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 2655 | 15181 | minor | |
| 2492 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings({"rawtypes", "unchecked"}) public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler { protected final JMXAgentContext agentContext; protected StandardMBean mbean; protected final AtomicLong trackedId = new AtomicLong(); /** * * @param agentContext * @param filter */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) { super(agentContext.getBundleContext(), filter, null); this.agentContext = agentContext; } /** * * @param agentContext * @param clazz */ protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) { super(agentContext.getBundleContext(), clazz, null); this.agentContext = agentContext; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Logger logger = agentContext.getLogger(); Object trackedService = null; long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); //API stipulates versions for compendium services with static ObjectName //This shouldn't happen but added as a consistency check if (trackedId.compareAndSet(0, serviceId)) { logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceId + "]"); trackedService = context.getService(reference); mbean = constructInjectMBean(trackedService); agentContext.registerMBean(AbstractCompendiumHandler.this); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed"); } return trackedService; } /* * (non-Javadoc) * * @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { Logger logger = agentContext.getLogger(); long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID); if (trackedId.compareAndSet(serviceID, 0)) { logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with " + Constants.SERVICE_ID + " [" + serviceID + "]"); agentContext.unregisterMBean(AbstractCompendiumHandler.this); context.ungetService(reference); } else { String serviceDescription = getServiceDescription(reference); logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with " + Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed"); } } private String getServiceDescription(ServiceReference reference) { String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION); if (serviceDescription == null) { Object obj = reference.getProperty(Constants.OBJECTCLASS); if (obj instanceof String[]) { StringBuilder sb = new StringBuilder(); for (String s : (String[]) obj) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } serviceDescription = sb.toString(); } else { serviceDescription = obj.toString(); } } return serviceDescription; } /** * Gets the StandardMBean managed by this handler when the backing service is available or null * * @see org.apache.aries.jmx.MBeanHandler#getMbean() */ public StandardMBean getMbean() { return mbean; } /** * Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied * service tracked by this handler * * @param targetService * the compendium service tracked by this handler * @return The StandardMBean instance whose registration lifecycle will be managed by this handler */ protected abstract StandardMBean constructInjectMBean(Object targetService); /** * The base name of the MBean. Will be expanded with the framework name and the UUID. * @return */ protected abstract String getBaseName(); /** * @see org.apache.aries.jmx.MBeanHandler#getName() */ public String getName() { return ObjectNameUtils.createFullObjectName(context, getBaseName()); } } |
blob | blob, long method | t | t | t | long method | 0 | 14622 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java/#L43-L166 | 1 | 2492 | 14622 | minor | |
| 4044 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10690 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 4044 | 10690 | critical | ||
| 3290 | YES, I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | Feature envy | t | f | t | 0 | 5783 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 3290 | 5783 | minor | ||
| 254 | { "message": "YES I found bad smells", "bad smells are": ["1.Long method"] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1.long method | t | t | t | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 254 | 2738 | critical | ||
| 1947 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 1947 | 12523 | major | ||
| 198 | {"message": "YES I found bad smells", "the bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 2238 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 198 | 2238 | major | |
| 2306 | YES I found bad smells" 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 2 | 2306 | 14069 | minor | ||
| 2221 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 2221 | 13553 | major | |
| 1653 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11584 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 1653 | 11584 | minor | ||
| 1032 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9387 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1032 | 9387 | minor | ||
| 2699 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 15326 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 2699 | 15326 | minor | ||
| 1714 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Document public class Customer extends AbstractDocument { private String firstname, lastname; @Field("email") @Indexed(unique = true) private EmailAddress emailAddress; private Set addresses = new HashSet(); /** * Creates a new {@link Customer} from the given firstname and lastname. * * @param firstname must not be {@literal null} or empty. * @param lastname must not be {@literal null} or empty. */ public Customer(String firstname, String lastname) { Assert.hasText(firstname); Assert.hasText(lastname); this.firstname = firstname; this.lastname = lastname; } protected Customer() { } /** * Adds the given {@link Address} to the {@link Customer}. * * @param address must not be {@literal null}. */ public void add(Address address) { Assert.notNull(address); this.addresses.add(address); } /** * Returns the firstname of the {@link Customer}. * * @return */ public String getFirstname() { return firstname; } /** * Returns the lastname of the {@link Customer}. * * @return */ public String getLastname() { return lastname; } /** * Sets the lastname of the {@link Customer}. * * @param lastname */ public void setLastname(String lastname) { this.lastname = lastname; } /** * Returns the {@link EmailAddress} of the {@link Customer}. * * @return */ public EmailAddress getEmailAddress() { return emailAddress; } /** * Sets the {@link Customer}'s {@link EmailAddress}. * * @param emailAddress must not be {@literal null}. */ public void setEmailAddress(EmailAddress emailAddress) { this.emailAddress = emailAddress; } /** * Return the {@link Customer}'s addresses. * * @return */ public Set getAddresses() { return Collections.unmodifiableSet(addresses); } } |
data class | Data Class | t | f | t | 0 | 11776 | https://github.com/spring-projects/spring-data-book/blob/3a9d2e35184d5361f1d305f4eb84b5febf87b992/mongodb/src/main/java/com/oreilly/springdata/mongodb/core/Customer.java/#L32-L125 | 1 | 1714 | 11776 | minor | ||
| 3909 | { "message": "YES I found bad smells", "bad smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | 1. data class | t | t | t | 0 | 10235 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 1 | 3909 | 10235 | minor | ||
| 1224 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1224 | 10343 | minor | ||
| 1547 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase) 4. Magic numbers (numerical values assigned without explanation) 5. Use of ArrayList instead of List interface 6. Use of comment block instead of proper documentation 7. Overloaded constructor with multiple arguments 8. Boolean flag parameters in addAttribute() method 9. Large number of parameters in addElement() and addAttribute() methods 10. Hard-coded values instead of using constants or variables 11. Unused variables/reserved word "res" 12. Poorly named variables (e.g. "cod | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | Long method2 Feature envy3 Inconsistent naming conventions (some elements and attributes use uppercase while others use lowercase)4 Magic numbers (numerical values assigned without explanation)5 Use of ArrayList instead of List interface6 Use of comment block instead of proper documentation 7 Overloaded constructor with multiple arguments 8 Boolean flag parameters in addAttribute() method 9 Large number of parameters in addElement() and addAttribute() methods | t | f | t | 0 | 11256 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 2 | 1547 | 11256 | critical | ||
| 1241 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10410 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 1241 | 10410 | major | ||
| 71 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XPathConstants { /** * Private constructor to prevent instantiation. */ private XPathConstants() { } /** * The XPath 1.0 number data type. * * Maps to Java {@link Double}. */ public static final QName NUMBER = new QName("http://www.w3.org/1999/XSL/Transform", "NUMBER"); /** * The XPath 1.0 string data type. * * Maps to Java {@link String}. */ public static final QName STRING = new QName("http://www.w3.org/1999/XSL/Transform", "STRING"); /** * The XPath 1.0 boolean data type. * * Maps to Java {@link Boolean}. */ public static final QName BOOLEAN = new QName("http://www.w3.org/1999/XSL/Transform", "BOOLEAN"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.NodeList}. */ public static final QName NODESET = new QName("http://www.w3.org/1999/XSL/Transform", "NODESET"); /** * The XPath 1.0 NodeSet data type. * * Maps to Java {@link org.w3c.dom.Node}. */ public static final QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE"); /** * The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom". */ public static final String DOM_OBJECT_MODEL = "http://java.sun.com/jaxp/xpath/dom"; } |
data class | data class | t | t | t | 0 | 1103 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/xpath/XPathConstants.java/#L32-L78 | 1 | 71 | 1103 | critical | ||
| 2373 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | long method, data class | t | t | t | long method | 0 | 14312 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 2373 | 14312 | minor | |
| 631 | { "output": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 1 | 631 | 6291 | minor | |
| 5648 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11201 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5648 | 11201 | major | |
| 635 | { "message": "YES I found bad smells", "detected_bad_smells": "The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 635 | 6305 | major | ||
| 4001 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10574 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 4001 | 10574 | major | ||
| 3794 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 9585 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 3794 | 9585 | minor | |
| 2901 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 2195 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 2901 | 2195 | major | |
| 756 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7049 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 2 | 756 | 7049 | minor | |
| 296 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BaseClassInfo { //~ Instance fields ---------------------------------------------------------------------------------------------------------- protected String name; protected String nameAndLoader; // A combinarion of class name and loader, uniquely identifying this ClassInfo // Management of multiple versions for the same-named (but possibly not same-code) class, loaded by different classloaders protected int classLoaderId; // IDs of all loaders with which versions of this class are loaded // Data used by our object allocation instrumentation mechanism: integer class ID private int instrClassId; //~ Constructors ------------------------------------------------------------------------------------------------------------- public BaseClassInfo(String className, int classLoaderId) { this.name = className.intern(); this.classLoaderId = classLoaderId; nameAndLoader = (name + "#" + classLoaderId).intern(); // NOI18N instrClassId = -1; } //~ Methods ------------------------------------------------------------------------------------------------------------------ public void setInstrClassId(int id) { instrClassId = id; } public int getInstrClassId() { return instrClassId; } public void setLoaderId(int loaderId) { classLoaderId = loaderId; } public int getLoaderId() { return classLoaderId; } public String getName() { return name; } public String getNameAndLoader() { return nameAndLoader; } public String toString() { return name; } } |
data class | data class, long method | t | t | t | long method | 0 | 3115 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/lib.profiler/src/org/graalvm/visualvm/lib/jfluid/classfile/BaseClassInfo.java/#L53-L103 | 1 | 296 | 3115 | major | |
| 2634 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | data class | t | t | t | 0 | 15114 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2634 | 15114 | minor | ||
| 2366 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | blob, data class | t | t | t | blob | 0 | 14296 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 1 | 2366 | 14296 | major | |
| 2368 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | long method, data class | t | t | t | data class | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 2368 | 14301 | minor | |
| 1119 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9960 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 1119 | 9960 | major | ||
| 2416 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 14420 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 2416 | 14420 | minor | |
| 350 | { "message": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ClusterServiceArtifactResponse { @ApiModelProperty(name = ArtifactResourceProvider.RESPONSE_KEY) @SuppressWarnings("unused") ClusterServiceArtifactResponseInfo getClusterServiceArtifactResponseInfo(); @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_DATA_PROPERTY) Map getArtifactData(); interface ClusterServiceArtifactResponseInfo { @ApiModelProperty(name = ArtifactResourceProvider.ARTIFACT_NAME) String getArtifactName(); @ApiModelProperty(name = ArtifactResourceProvider.CLUSTER_NAME) String getClusterName(); @ApiModelProperty(name = ArtifactResourceProvider.SERVICE_NAME) String getServiceName(); } } |
data class | blob, data class | t | t | t | blob | 0 | 3597 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/ClusterServiceArtifactResponse.java/#L32-L52 | 1 | 350 | 3597 | major | |
| 1027 | {"message": "YES I found bad smells", "bad smells are": "1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | 1. long method | t | t | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1027 | 9370 | major | ||
| 3589 | the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Long method2 Feature envy | f | f | t | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 3589 | 7923 | major | ||
| 924 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8307 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 924 | 8307 | minor | |
| 1588 | YES I found bad smells The bad smells are: 1.Method with multiple responsibilities 2. Complex conditional logic 3. Long method 4. Feature envy 5. Duplicate code 6. Dependency on specific implementation 7. Dependency on specific feature | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Method with multiple responsibilities2 Complex conditional logic3 Long method4 Feature envy5 Duplicate code6 Dependency on specific implementation7 Dependency on specific feature | t | f | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 1588 | 11376 | major | ||
| 1512 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Repeated code, 3. Feature envy, 4. Nested if statements, 5. Catch blocks for multiple exceptions, 6. Use of primitive types instead of reference types, 7. Use of unnecessary temporary variables, 8. Inconsistent naming convention, 9. Mixing business logic with data retrieval, 10. Lack of comments explaining complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
feature envy | Long method, 2 Repeated code, 3 Feature envy, 4 Nested if statements, 5 Catch blocks for multiple exceptions, 6 Use of primitive types instead of reference types, 7 Use of unnecessary temporary variables, 8 Inconsistent naming convention, 9 Mixing business logic with data retrieval, | t | f | t | . Long method, 2. Repeated code, 4. Nested if statements, 5. Catch blocks for multiple exceptions, 6. Use of primitive types instead of reference types, 7. Use of unnecessary temporary variables, 8. Inconsistent naming convention, 9. Mixing business logic with data retrieval, | 0 | 11160 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1512 | 11160 | minor | |
| 4308 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | data class | t | t | t | 0 | 11355 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 4308 | 11355 | minor | ||
| 2302 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, data class | t | t | t | data class | 0 | 14043 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 2302 | 14043 | minor | |
| 776 | {"response":"YES I found bad smells","bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class, long method | t | t | t | long method | 0 | 7362 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 776 | 7362 | major | |
| 5381 | { "output": "YES I found bad smells", "the bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class | t | t | t | 0 | 15120 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 5381 | 15120 | minor | ||
| 2450 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14505 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2450 | 14505 | minor | |
| 955 | {"message":"YES I found bad smells","bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiResponse200 { private String message; private int code; private long t200; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public long getT200() { return t200; } public void setT200(long t200) { this.t200 = t200; } } |
data class | data class | t | t | t | 0 | 8535 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/multiErrorCode/MultiResponse200.java/#L20-L50 | 1 | 955 | 8535 | major | ||
| 1785 | YES I found bad smells: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11978 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 1785 | 11978 | minor | ||
| 1432 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method, data class | t | t | t | data class | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 1432 | 10956 | minor | |
| 1520 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1520 | 11172 | minor | ||
| 1082 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSystemFactoryBean implements InitializingBean, DisposableBean, FactoryBean { private FileSystem fs; private Configuration configuration; private URI uri; private String user; private boolean closeAll = false; private boolean close = true; public void afterPropertiesSet() throws Exception { Configuration cfg = (configuration != null ? configuration : new Configuration(true)); if (uri == null) { uri = FileSystem.getDefaultUri(cfg); } if (StringUtils.hasText(user)) { fs = FileSystem.get(uri, cfg, user); } else { fs = FileSystem.get(uri, cfg); } } public void destroy() throws Exception { if (fs != null && close) { fs.close(); } fs = null; if (closeAll) { // TODO: potentially call close all just for the current user FileSystem.closeAll(); } } public FileSystem getObject() throws Exception { return fs; } public Class getObjectType() { return (fs != null ? fs.getClass() : FileSystem.class); } public boolean isSingleton() { return true; } /** * Sets the Hadoop configuration for this file system. * * @param configuration The configuration to set. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Sets the URI (if available) for this file system. * * @param uri The uri to set. */ public void setUri(URI uri) { this.uri = uri; } /** * Sets the user impersonation (optional) for creating this file-system. * Should be used when running against a Hadoop Kerberos cluster. * * @param user user/group information */ public void setUser(String user) { this.user = user; } /** * Indicates whether all the Hadoop file systems should be closed once this factory is destroyed. * False by default - should be turned on as a safety measure when the app controls the entire lifecycle of Hadoop inside * a JVM. * * @param closeAll the close all * @see FileSystem#closeAll() */ public void setCloseAll(boolean closeAll) { this.closeAll = closeAll; } /** * Indicates whether the Hadoop file systems should be closed once this factory is destroyed. * True by default - should be turned off when running 'embedded' or if long running operations outlive the application context. * * @param close close * @see FileSystem#close() */ public void setClose(boolean close) { this.close = close; } } |
data class | data class | t | t | t | 0 | 9684 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-hadoop-core/src/main/java/org/springframework/data/hadoop/fs/FileSystemFactoryBean.java/#L34-L131 | 1 | 1082 | 9684 | minor | ||
| 1321 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10698 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 1321 | 10698 | minor | ||
| 2046 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers/strings 3. Feature envy 4. Testing multiple scenarios within a single test method 5. Lack of proper comments/documentation 6. Lack of clear and concise variable names 7. Unnecessary/redundant code (e.g. using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers/strings3 Feature envy4 Testing multiple scenarios within a single test method5 Lack of proper comments/documentation6 Lack of clear and concise variable names7 Unnecessary/redundant code (eg using assertEquals and assertTrue separately when the same result can be achieved with a single assertion) | t | f | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 2046 | 12872 | minor | ||
| 596 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | data class, long method | t | t | t | long method | 0 | 5950 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 1 | 596 | 5950 | minor | |
| 130 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ParseSpec withTimestampSpec(TimestampSpec spec) { return new TimeAndDimsParseSpec(spec, getDimensionsSpec()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1610 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/data/input/impl/TimeAndDimsParseSpec.java/#L70-L74 | 2 | 130 | 1610 | minor | |
| 1603 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1603 | 11438 | minor | ||
| 2333 | {"message": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 14159 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 2333 | 14159 | minor | |
| 612 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void serialize(AGeometry instance, DataOutput out) throws HyracksDataException { try { OGCGeometry geometry = instance.getGeometry(); byte[] buffer = geometry.asBinary().array(); // For efficiency, we store the size of the geometry in bytes in the first 32 bits // This allows AsterixDB to skip over this attribute if needed. out.writeInt(buffer.length); out.write(buffer); } catch (IOException e) { throw HyracksDataException.create(e); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 6154 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-om/src/main/java/org/apache/asterix/dataflow/data/nontagged/serde/AGeometrySerializerDeserializer.java/#L63-L75 | 2 | 612 | 6154 | major | |
| 2401 | { "response": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14380 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 2401 | 14380 | minor | |
| 1190 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1190 | 10253 | critical | ||
| 1031 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Useless comments (ex: "@Override @MultiMQAdminCmdMethod") 4. Use of multiple catch statements for different exceptions 5. Nested for loops and try-catch statements 6. Repeated code (ex: calling mqAdminExt.resetOffsetByTimestamp twice) 7. Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList) 8. Lack of encapsulation/abstraction (ex: direct access to class attributes) 9. Use of Maps and Lists instead of more object-oriented data structures 10. Nested if-else statements 11. Use of continue statement to skip code (ex: "continue;" in the catch block) 12. Lack of exception handling techniques like throwing/catching custom exceptions 13. Lack of separation of concerns (resetOffset method has multiple responsibilities) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy3 Useless comments (ex: "@Override @MultiMQAdminCmdMethod")4 Use of multiple catch statements for different exceptions5 Nested for loops and try-catch statements6 Repeated code (ex: calling mqAdminExtresetOffsetByTimestamp twice)7 Poor variable naming (ex: groupRollbackStats, rollbackStats, rollbackStatsMap, rollbackStatsList)8 Lack of encapsulation/abstraction (ex: direct access to class attributes)9 Use of Maps and Lists instead of more object-oriented data structures | t | f | t | rollbackStats, rollbackStatsMap, rollbackStatsList)8. Lack of encapsulation/abstraction (ex: direct access to class attributes)9. Use of Maps and Lists instead of more object-oriented data structures | 0 | 9386 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 1031 | 9386 | major | |
| 1301 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Data class, 4. Data clumps, 5. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | Long method, 2 Feature envy, 3 Data class, 4 Data clumps, 5 Primitive obsession | t | f | t | . Long method, 2. Feature envy, 4. Data clumps, 5. Primitive obsession | 0 | 10658 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 2 | 1301 | 10658 | minor | |
| 1033 | YES I found bad smells The bad smells are: 1. Long method 2. Exception throwing (multiple exceptions in method signature) 3. Dependency on specific library (java.util.concurrent) 4. Inconsistent variable naming conventions 5. Multiple nested if statements 6. Lack of comments or documentation explaining the purpose of the method and its parameters 7. Possible synchronization issues (using wait() without a corresponding notify() or notifyAll()) 8. Code duplication (using the same code to check for internalFuture and to calculate remaining time) 9. Hard to read and understand code flow due to excessive use of ternary operator (? and :) 10. Magic numbers (1, TimeUnit.MILLISECONDS) used without explanation or context. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method2 Exception throwing (multiple exceptions in method signature)3 Dependency on specific library (javautilconcurrent)4 Inconsistent variable naming conventions5 Multiple nested if statements6 Lack of comments or documentation explaining the purpose of the method and its parameters7 Possible synchronization issues (using wait() without a corresponding notify() or notifyAll())8 Code duplication (using the same code to check for internalFuture and to calculate remaining time)9 Hard to read and understand code flow due to excessive use of ternary operator (? and :) | t | f | t | 0 | 9391 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 1033 | 9391 | minor | ||
| 639 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | data class | t | t | t | 0 | 6330 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 639 | 6330 | critical | ||
| 2597 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 2597 | 15009 | minor | ||
| 693 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method, data class | t | t | t | data class | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 693 | 6654 | major | |
| 2515 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | data class | t | t | t | 0 | 14695 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 1 | 2515 | 14695 | major | ||
| 1842 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 1842 | 12151 | major | ||
| 1686 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
blob | Blob | t | f | t | 0 | 11687 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 1 | 1686 | 11687 | minor | ||
| 1211 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10310 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 1211 | 10310 | critical | |
| 1217 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Inconsistent formatting 5. Poor naming conventions (e.g. "sql", "sel", "params") 6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks) 7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()") 8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause") 9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) 10. Lack of comments and documentation on the purpose and logic of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code4 Inconsistent formatting5 Poor naming conventions (eg "sql", "sel", "params")6 Possible code duplication (eg in the "if (updateParams == null)" and "else" blocks)7 Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8 Possible excessive use of boolean flags (eg "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9 Possible violation of SOLID principles (eg Single Responsibility, Open/Closed) | t | f | t | "sel", "params")6. Possible code duplication (e.g. in the "if (updateParams == null)" and "else" blocks)7. Possible tight coupling to specific database implementation (referring to database-specific language like "deleteTargets" and "getFullName()")8. Possible excessive use of boolean flags (e.g. "requiresTargetForDelete", "supportsSubselect", "supportsCorrelatedSubselect", "allowsAliasInBulkClause")9. Possible violation of SOLID principles (e.g. Single Responsibility, Open/Closed) | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1217 | 10323 | major | |
| 3570 | {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
blob | blob, data class | t | t | t | data class | 0 | 7852 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 3570 | 7852 | minor | |
| 3437 | { "message": "YES I found bad smells", "bad smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | blob, data class | t | t | t | blob | 0 | 6831 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 1 | 3437 | 6831 | minor | |
| 2310 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14096 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2310 | 14096 | major | ||
| 461 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 2 | 461 | 4463 | minor | ||
| 1603 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long Method | t | f | t | 0 | 11438 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1603 | 11438 | minor | ||
| 847 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | data class | t | t | t | 0 | 7836 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 847 | 7836 | minor | ||
| 394 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 394 | 3978 | minor | ||
| 397 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void configure(final Marshaller marshaller) { marshaller.setAdapter(PersistentEntityAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntityAdapter())); marshaller.setAdapter(PersistentEntitiesAdapter.class, serviceRegistry.injectServicesInto(new PersistentEntitiesAdapter())); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 4060 | https://github.com/apache/isis/blob/2af2ef3e2edcb807d742f089839e0571d8132bd9/core/applib/src/main/java/org/apache/isis/schema/services/jaxb/JaxbServiceDefault.java/#L93-L99 | 1 | 397 | 4060 | major |
| 2865 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | data class | t | t | t | 0 | 1975 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2865 | 1975 | minor | ||
| 5771 | YES, I found bad smells the bad smells are: 1. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
long method | Long method | t | f | t | 0 | 14811 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5771 | 14811 | minor | ||
| 5781 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5781 | 15317 | minor | ||
| 1440 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | long method | t | t | t | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 1 | 1440 | 10972 | minor | ||
| 1359 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Switch statement 4. State variable usage 5. Feature envy (using input stream methods instead of TokenStream methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2 Duplicate code3 Switch statement4 State variable usage5 Feature envy (using input stream methods instead of TokenStream methods) | t | f | t | 0 | 10776 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1359 | 10776 | major | ||
| 1011 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9271 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1011 | 9271 | minor | ||
| 1371 | {"response": "YES I found bad smells", "bad_smells": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Whitespace implements Text { private String text; public Whitespace(String text) { this.text = text; } @Override public String getText() { return text; } } |
data class | 2. data class | t | t | t | 0 | 10800 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/common/src/org/eclipse/ceylon/common/config/ConfigWriter.java/#L395-L404 | 1 | 1371 | 10800 | major | ||
| 995 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9092 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 2 | 995 | 9092 | major | |
| 1143 | { "message": "YES I found bad smells", "bad smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
blob | blob, long method | t | t | t | long method | 0 | 10101 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 1 | 1143 | 10101 | minor | |
| 5180 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Divergent change 6. Temporary field 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class AddEditNameUrlDialog extends Dialog { AbstractNameUrlPreferenceModel model; Text nameText; Text urlText; String name; String urlString; private final String explanatoryText; protected Label errorTextLabel; protected Composite composite; private String title; public AddEditNameUrlDialog(Shell parent, AbstractNameUrlPreferenceModel aModel, NameUrlPair nameUrl, String headerText) { super(parent); explanatoryText = headerText; model = aModel; if (nameUrl != null) { name = nameUrl.getName(); urlString = nameUrl.getUrlString(); } else { name = null; urlString = null; } } @Override protected Control createDialogArea(Composite parent) { composite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).extendedMargins(5, 13, 10, 0).applyTo(composite); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); Label explanatoryTextLabel = new Label(composite, SWT.WRAP); explanatoryTextLabel.setText(explanatoryText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(explanatoryTextLabel); Label nameLabel = new Label(composite, SWT.NONE); nameLabel.setText(NLS.bind("Name:", null)); nameLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); nameText = new Text(composite, SWT.BORDER + SWT.FILL); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(nameText); nameText.setEditable(true); if (name != null && name.length() > 0) { nameText.setText(name); } Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(NLS.bind("URL:", null)); urlLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); urlText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).hint(300, SWT.DEFAULT).applyTo(urlText); urlText.setEditable(true); if (urlString != null && urlString.length() > 0) { urlText.setText(urlString); } urlText.addKeyListener(getUrlValidationListener()); String errorText = ""; errorTextLabel = new Label(composite, SWT.WRAP); errorTextLabel.setText(errorText); GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(errorTextLabel); // getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); return composite; } @Override public void create() { super.create(); if (title != null) { getShell().setText(title); } getButton(IDialogConstants.OK_ID).setEnabled(validateUrl(urlString)); } protected KeyListener getUrlValidationListener() { return new KeyListener() { public void keyReleased(KeyEvent e) { String urlString = ((Text) e.getSource()).getText().trim(); if (!validateUrl(urlString)) { getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorTextLabel.setText(""); composite.update(); getButton(IDialogConstants.OK_ID).setEnabled(true); } } public void keyPressed(KeyEvent e) { // do nothing } }; } @Override protected void okPressed() { name = nameText.getText(); urlString = urlText.getText(); if (urlString.length() > 0) { if (name.length() <= 0) { name = urlString; } } super.okPressed(); } public String getUrlString() { return urlString; } public String getName() { return name; } protected boolean validateUrl(String urlString) { if (urlString != null && urlString.contains(" ")) { urlString = urlString.replace(" ", "%20"); int caret = urlText.getCaretPosition(); urlText.setText(urlString); urlText.setSelection(caret + "%20".length() - 1); } if (urlString == null || urlString.length() <= 0) { return false; } try { new URI(urlString); } catch (URISyntaxException e) { return showError(); } try { URL url = new URL(urlString); if (url.getHost().isEmpty()) { return showError(); } } catch (MalformedURLException e) { return showError(); } return true; } private boolean showError() { errorTextLabel.setText(AddEditNameUrlDialogMessages.malformedUrl); composite.update(); return false; } protected void setTitle(String title) { this.title = title; } } |
data class | Long method2 Feature envy3 Data class4 Primitive obsession5 Divergent change6 Temporary field7 Lazy class | t | f | t | 0 | 14486 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/util/AddEditNameUrlDialog.java/#L38-L208 | 2 | 5180 | 14486 | minor | ||
| 2476 | {"response":"YES I found bad smells","bad smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractGroupingProperty { protected Set columnSet; public AbstractGroupingProperty(Set columnSet) { this.columnSet = columnSet; } public Set getColumnSet() { return columnSet; } // Returns normalized and concise columns from an input column set, by considering // equivalence classes and functional dependencies. protected Set normalizeAndReduceGroupingColumns(Set columns, Map equivalenceClasses, List fds) { Set normalizedColumnSet = getNormalizedColumnsAccordingToEqClasses(columns, equivalenceClasses); reduceGroupingColumns(normalizedColumnSet, fds); return normalizedColumnSet; } // Gets normalized columns, where each column variable is a representative variable of its equivalence class, // therefore, the matching of properties will can consider equivalence classes. private Set getNormalizedColumnsAccordingToEqClasses(Set columns, Map equivalenceClasses) { Set normalizedColumns = new ListSet<>(); if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { normalizedColumns.addAll(columns); return normalizedColumns; } for (LogicalVariable v : columns) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { normalizedColumns.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { normalizedColumns.add(ec.getVariableRepresentative()); } } } return normalizedColumns; } // Using functional dependencies to eliminate unnecessary columns. private void reduceGroupingColumns(Set columnSet, List fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set norm = new ListSet<>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet.retainAll(norm); } } |
data class | long method, data class | t | t | t | long method | 0 | 14587 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java/#L29-L99 | 1 | 2476 | 14587 | minor | |
| 2822 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 1499 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 2822 | 1499 | major | ||
| 2590 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class FloatFilterFunction extends AbstractFloatValue { private final FloatValue baseExpr; private final BooleanValue filterExpr; public static final String name = FilterFunction.name; private final String exprStr; private final ExpressionType funcType; public FloatFilterFunction(FloatValue baseExpr, BooleanValue filterExpr) throws SolrException { this.baseExpr = baseExpr; this.filterExpr = filterExpr; this.exprStr = AnalyticsValueStream.createExpressionString(name,baseExpr,filterExpr); this.funcType = AnalyticsValueStream.determineMappingPhase(exprStr,baseExpr,filterExpr); } boolean exists = false; @Override public float getFloat() { float value = baseExpr.getFloat(); exists = baseExpr.exists() && filterExpr.getBoolean() && filterExpr.exists(); return value; } @Override public boolean exists() { return exists; } @Override public String getName() { return name; } @Override public String getExpressionStr() { return exprStr; } @Override public ExpressionType getExpressionType() { return funcType; } } |
data class | data class, long method | t | t | t | long method | 0 | 14997 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/contrib/analytics/src/java/org/apache/solr/analytics/function/mapping/FilterFunction.java/#L462-L501 | 1 | 2590 | 14997 | critical | |
| 1934 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 12462 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 1934 | 12462 | major | ||
| 3290 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5783 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 3290 | 5783 | minor | |
| 354 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } } |
blob | blob, long method | t | t | t | long method | 0 | 3651 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 | 1 | 354 | 3651 | major | |
| 1489 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | data class, long method | t | t | t | long method | 0 | 11106 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 1 | 1489 | 11106 | major | |
| 861 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are: 1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); if (logger.isDebugEnabled()) { logger.debug("Voter: " + voter + ", returned: " + result); } switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions(); } |
long method | the bad smells are: 1. long method | t | t | t | 0 | 7903 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/vote/AffirmativeBased.java/#L58-L90 | 1 | 861 | 7903 | minor | ||
| 152 | { "response": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1930 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 152 | 1930 | major | |
| 2326 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 2326 | 14143 | minor | |
| 2297 | YES, I found bad smells: 1. Long method 2. Complex code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Complex code | t | f | t | 0 | 14024 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 2297 | 14024 | major | ||
| 513 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 513 | 5219 | minor | ||
| 1922 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | data class | t | t | t | 0 | 12425 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 1 | 1922 | 12425 | major | ||
| 999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | long method | t | t | t | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 999 | 9162 | major | ||
| 1710 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 1710 | 11765 | major | |
| 1697 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class ComparerHolder { static final String UNSAFE_COMPARER_NAME = ComparerHolder.class.getName() + "$UnsafeComparer"; static final Comparer BEST_COMPARER = getBestComparer(); static Comparer getBestComparer() { try { Class theClass = Class.forName(UNSAFE_COMPARER_NAME); @SuppressWarnings("unchecked") Comparer comparer = (Comparer) theClass.getConstructor().newInstance(); return comparer; } catch (Throwable t) { // ensure we really catch *everything* return PureJavaComparer.INSTANCE; } } static final class PureJavaComparer extends Comparer { static final PureJavaComparer INSTANCE = new PureJavaComparer(); private PureJavaComparer() {} @Override public int compareTo(byte [] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1[i] & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { int end1 = o1 + l1; int end2 = o2 + l2; for (int i = o1, j = o2; i < end1 && j < end2; i++, j++) { int a = buf1.get(i) & 0xFF; int b = buf2.get(j) & 0xFF; if (a != b) { return a - b; } } return l1 - l2; } } static final class UnsafeComparer extends Comparer { public UnsafeComparer() {} static { if(!UNSAFE_UNALIGNED) { throw new Error(); } } @Override public int compareTo(byte[] buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset2Adj; Object refObj2 = null; if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer)buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(buf1, o1 + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET, l1, refObj2, offset2Adj, l2); } @Override public int compareTo(ByteBuffer buf1, int o1, int l1, ByteBuffer buf2, int o2, int l2) { long offset1Adj, offset2Adj; Object refObj1 = null, refObj2 = null; if (buf1.isDirect()) { offset1Adj = o1 + ((DirectBuffer) buf1).address(); } else { offset1Adj = o1 + buf1.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj1 = buf1.array(); } if (buf2.isDirect()) { offset2Adj = o2 + ((DirectBuffer) buf2).address(); } else { offset2Adj = o2 + buf2.arrayOffset() + UnsafeAccess.BYTE_ARRAY_BASE_OFFSET; refObj2 = buf2.array(); } return compareToUnsafe(refObj1, offset1Adj, l1, refObj2, offset2Adj, l2); } } } |
blob | Blob, Data Class, Long Method | t | f | t | Data Class, Long Method | 0 | 11729 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/util/ByteBufferUtils.java/#L77-L171 | 1 | 1697 | 11729 | minor | |
| 1682 | return HiveAlgorithmsUtil.getJoinCumulativeMemoryWithinPhaseSplit(join); YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 1682 | 11682 | major | ||
| 804 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 804 | 7620 | minor | |
| 5057 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractControllerService extends AbstractConfigurableComponent implements ControllerService { private String identifier; private ControllerServiceLookup serviceLookup; private ComponentLog logger; private StateManager stateManager; private volatile ConfigurationContext configurationContext; private volatile boolean enabled = false; @Override public final void initialize(final ControllerServiceInitializationContext context) throws InitializationException { this.identifier = context.getIdentifier(); serviceLookup = context.getControllerServiceLookup(); logger = context.getLogger(); stateManager = context.getStateManager(); init(context); } @Override public String getIdentifier() { return identifier; } /** * @return the {@link ControllerServiceLookup} that was passed to the * {@link #init(ControllerServiceInitializationContext)} method */ protected final ControllerServiceLookup getControllerServiceLookup() { return serviceLookup; } /** * Provides a mechanism by which subclasses can perform initialization of * the Controller Service before it is scheduled to be run * * @param config of initialization context * @throws InitializationException if unable to init */ protected void init(final ControllerServiceInitializationContext config) throws InitializationException { } @OnEnabled public final void enabled() { this.enabled = true; } @OnDisabled public final void disabled() { this.enabled = false; } public boolean isEnabled() { return this.enabled; } /** * @return the logger that has been provided to the component by the * framework in its initialize method */ protected ComponentLog getLogger() { return logger; } /** * @return the StateManager that can be used to store and retrieve state for this Controller Service */ protected StateManager getStateManager() { return stateManager; } @OnEnabled public final void abstractStoreConfigContext(final ConfigurationContext configContext) { this.configurationContext = configContext; } @OnDisabled public final void abstractClearConfigContext() { this.configurationContext = null; } protected ConfigurationContext getConfigurationContext() { final ConfigurationContext context = this.configurationContext; if (context == null) { throw new IllegalStateException("No Configuration Context exists"); } return configurationContext; } protected PropertyValue getProperty(final PropertyDescriptor descriptor) { return getConfigurationContext().getProperty(descriptor); } } |
blob | blob | t | t | t | 0 | 14131 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-api/src/main/java/org/apache/nifi/controller/AbstractControllerService.java/#L28-L120 | 1 | 5057 | 14131 | minor | ||
| 1789 | YES, I found bad smells. The bad smells are: 1. Long method 2. Unnecessary complexity 3. Feature envy 4. Code duplication 5. Inappropriate coupling 6. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long method2 Unnecessary complexity3 Feature envy4 Code duplication5 Inappropriate coupling6 Incomplete error handling | t | f | t | 0 | 11985 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 1789 | 11985 | minor | ||
| 4227 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | data class | t | t | t | 0 | 11130 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 4227 | 11130 | critical | ||
| 2119 | {"response": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class", "Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteInterpreterEventServer implements RemoteInterpreterEventService.Iface { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInterpreterEventServer.class); private String portRange; private int port; private String host; private TThreadPoolServer thriftServer; private InterpreterSettingManager interpreterSettingManager; private final ScheduledExecutorService appendService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture appendFuture; private AppendOutputRunner runner; private final RemoteInterpreterProcessListener listener; private final ApplicationEventListener appListener; private final Gson gson = new Gson(); public RemoteInterpreterEventServer(ZeppelinConfiguration zConf, InterpreterSettingManager interpreterSettingManager) { this.portRange = zConf.getZeppelinServerRPCPortRange(); this.interpreterSettingManager = interpreterSettingManager; this.listener = interpreterSettingManager.getRemoteInterpreterProcessListener(); this.appListener = interpreterSettingManager.getAppEventListener(); } public void start() throws IOException { Thread startingThread = new Thread() { @Override public void run() { TServerSocket tSocket = null; try { tSocket = RemoteInterpreterUtils.createTServerSocket(portRange); port = tSocket.getServerSocket().getLocalPort(); host = RemoteInterpreterUtils.findAvailableHostAddress(); } catch (IOException e1) { throw new RuntimeException(e1); } LOGGER.info("InterpreterEventServer is starting at {}:{}", host, port); RemoteInterpreterEventService.Processor processor = new RemoteInterpreterEventService.Processor(RemoteInterpreterEventServer.this); thriftServer = new TThreadPoolServer( new TThreadPoolServer.Args(tSocket).processor(processor)); thriftServer.serve(); } }; startingThread.start(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) < 30 * 1000) { if (thriftServer != null && thriftServer.isServing()) { break; } try { Thread.sleep(500); } catch (InterruptedException e) { throw new IOException(e); } } if (thriftServer != null && !thriftServer.isServing()) { throw new IOException("Fail to start InterpreterEventServer in 30 seconds."); } LOGGER.info("RemoteInterpreterEventServer is started"); runner = new AppendOutputRunner(listener); appendFuture = appendService.scheduleWithFixedDelay( runner, 0, AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS); } public void stop() { if (thriftServer != null) { thriftServer.stop(); } if (appendFuture != null) { appendFuture.cancel(true); } LOGGER.info("RemoteInterpreterEventServer is stopped"); } public int getPort() { return port; } public String getHost() { return host; } @Override public void registerInterpreterProcess(RegisterInfo registerInfo) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(registerInfo.getInterpreterGroupId()); if (interpreterGroup == null) { LOGGER.warn("No such interpreterGroup: " + registerInfo.getInterpreterGroupId()); return; } RemoteInterpreterProcess interpreterProcess = ((ManagedInterpreterGroup) interpreterGroup).getInterpreterProcess(); if (interpreterProcess == null) { LOGGER.warn("Interpreter process does not existed yet for InterpreterGroup: " + registerInfo.getInterpreterGroupId()); } interpreterProcess.processStarted(registerInfo.port, registerInfo.host); } @Override public void appendOutput(OutputAppendEvent event) throws TException { if (event.getAppId() == null) { runner.appendBuffer( event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getData()); } else { appListener.onOutputAppend(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), event.getData()); } } @Override public void updateOutput(OutputUpdateEvent event) throws TException { if (event.getAppId() == null) { listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } else { appListener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), event.getIndex(), event.getAppId(), InterpreterResult.Type.valueOf(event.getType()), event.getData()); } } @Override public void updateAllOutput(OutputUpdateAllEvent event) throws TException { listener.onOutputClear(event.getNoteId(), event.getParagraphId()); for (int i = 0; i < event.getMsg().size(); i++) { RemoteInterpreterResultMessage msg = event.getMsg().get(i); listener.onOutputUpdated(event.getNoteId(), event.getParagraphId(), i, InterpreterResult.Type.valueOf(msg.getType()), msg.getData()); } } @Override public void appendAppOutput(AppOutputAppendEvent event) throws TException { appListener.onOutputAppend(event.noteId, event.paragraphId, event.index, event.appId, event.data); } @Override public void updateAppOutput(AppOutputUpdateEvent event) throws TException { appListener.onOutputUpdated(event.noteId, event.paragraphId, event.index, event.appId, InterpreterResult.Type.valueOf(event.type), event.data); } @Override public void updateAppStatus(AppStatusUpdateEvent event) throws TException { appListener.onStatusChange(event.noteId, event.paragraphId, event.appId, event.status); } @Override public void runParagraphs(RunParagraphsEvent event) throws TException { try { listener.runParagraphs(event.getNoteId(), event.getParagraphIndices(), event.getParagraphIds(), event.getCurParagraphId()); if (InterpreterContext.get() != null) { LOGGER.info("complete runParagraphs." + InterpreterContext.get().getParagraphId() + " " + event); } else { LOGGER.info("complete runParagraphs." + event); } } catch (IOException e) { throw new TException(e); } } @Override public void addAngularObject(String intpGroupId, String json) throws TException { LOGGER.debug("Add AngularObject, interpreterGroupId: " + intpGroupId + ", json: " + json); AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().add(angularObject.getName(), angularObject.get(), angularObject.getNoteId(), angularObject.getParagraphId()); } @Override public void updateAngularObject(String intpGroupId, String json) throws TException { AngularObject angularObject = AngularObject.fromJson(json); InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } AngularObject localAngularObject = interpreterGroup.getAngularObjectRegistry().get( angularObject.getName(), angularObject.getNoteId(), angularObject.getParagraphId()); if (localAngularObject instanceof RemoteAngularObject) { // to avoid ping-pong loop ((RemoteAngularObject) localAngularObject).set( angularObject.get(), true, false); } else { localAngularObject.set(angularObject.get()); } } @Override public void removeAngularObject(String intpGroupId, String noteId, String paragraphId, String name) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } interpreterGroup.getAngularObjectRegistry().remove(name, noteId, paragraphId); } @Override public void sendParagraphInfo(String intpGroupId, String json) throws TException { InterpreterGroup interpreterGroup = interpreterSettingManager.getInterpreterGroupById(intpGroupId); if (interpreterGroup == null) { throw new TException("Invalid InterpreterGroupId: " + intpGroupId); } Map paraInfos = gson.fromJson(json, new TypeToken>() { }.getType()); String noteId = paraInfos.get("noteId"); String paraId = paraInfos.get("paraId"); String settingId = RemoteInterpreterUtils. getInterpreterSettingId(interpreterGroup.getId()); if (noteId != null && paraId != null && settingId != null) { listener.onParaInfosReceived(noteId, paraId, settingId, paraInfos); } } @Override public List getAllResources(String intpGroupId) throws TException { ResourceSet resourceSet = getAllResourcePoolExcept(intpGroupId); List resourceList = new LinkedList<>(); for (Resource r : resourceSet) { resourceList.add(r.toJson()); } return resourceList; } @Override public ByteBuffer getResource(String resourceIdJson) throws TException { ResourceId resourceId = ResourceId.fromJson(resourceIdJson); Object o = getResource(resourceId); ByteBuffer obj; if (o == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(o); } catch (IOException e) { throw new TException(e); } } return obj; } /** * * @param intpGroupId caller interpreter group id * @param invokeMethodJson invoke information * @return * @throws TException */ @Override public ByteBuffer invokeMethod(String intpGroupId, String invokeMethodJson) throws TException { InvokeResourceMethodEventMessage invokeMethodMessage = InvokeResourceMethodEventMessage.fromJson(invokeMethodJson); Object ret = invokeResourceMethod(intpGroupId, invokeMethodMessage); ByteBuffer obj = null; if (ret == null) { obj = ByteBuffer.allocate(0); } else { try { obj = Resource.serializeObject(ret); } catch (IOException e) { LOGGER.error("invokeMethod failed", e); } } return obj; } @Override public List getParagraphList(String user, String noteId) throws TException, ServiceException { LOGGER.info("get paragraph list from remote interpreter noteId: " + noteId + ", user = " + user); if (user != null && noteId != null) { List paragraphInfos = listener.getParagraphList(user, noteId); return paragraphInfos; } else { LOGGER.error("user or noteId is null!"); return null; } } private Object invokeResourceMethod(String intpGroupId, final InvokeResourceMethodEventMessage message) { final ResourceId resourceId = message.resourceId; ManagedInterpreterGroup intpGroup = interpreterSettingManager.getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { Resource res = localPool.get(resourceId.getName()); if (res != null) { try { return res.invokeMethod( message.methodName, message.getParamTypes(), message.params, message.returnResourceName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else { // object is null. can't invoke any method LOGGER.error("Can't invoke method {} on null object", message.methodName); return null; } } else { LOGGER.error("no resource pool"); return null; } } else if (remoteInterpreterProcess.isRunning()) { ByteBuffer res = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceInvokeMethod( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName(), message.toJson()); } } ); try { return Resource.deserializeObject(res); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } return null; } private Object getResource(final ResourceId resourceId) { ManagedInterpreterGroup intpGroup = interpreterSettingManager .getInterpreterGroupById(resourceId.getResourcePoolId()); if (intpGroup == null) { return null; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); ByteBuffer buffer = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction() { @Override public ByteBuffer call(RemoteInterpreterService.Client client) throws Exception { return client.resourceGet( resourceId.getNoteId(), resourceId.getParagraphId(), resourceId.getName()); } } ); try { Object o = Resource.deserializeObject(buffer); return o; } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private ResourceSet getAllResourcePoolExcept(String interpreterGroupId) { ResourceSet resourceSet = new ResourceSet(); for (ManagedInterpreterGroup intpGroup : interpreterSettingManager.getAllInterpreterGroup()) { if (intpGroup.getId().equals(interpreterGroupId)) { continue; } RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess(); if (remoteInterpreterProcess == null) { ResourcePool localPool = intpGroup.getResourcePool(); if (localPool != null) { resourceSet.addAll(localPool.getAll()); } } else if (remoteInterpreterProcess.isRunning()) { List resourceList = remoteInterpreterProcess.callRemoteFunction( new RemoteInterpreterProcess.RemoteFunction>() { @Override public List call(RemoteInterpreterService.Client client) throws Exception { return client.resourcePoolGetAll(); } } ); for (String res : resourceList) { resourceSet.add(RemoteResource.fromJson(res)); } } } return resourceSet; } } |
blob | blob, data class, feature envy, long method | t | t | t | data class, feature envy, long method | 0 | 13201 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RemoteInterpreterEventServer.java/#L66-L485 | 1 | 2119 | 13201 | major | |
| 464 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Cel4rreg { long seghigh; long seglow; int p_dsafmt = -1; long p_dsaptr; RegisterSet regs; /** * Creates the instance and attempts to locate the registers. */ Cel4rreg() { /* Debug option - before we do anything else, try using the old svcdump code */ String useSvcdump = System.getProperty("zebedee.use.svcdump"); if (useSvcdump != null && useSvcdump.equals("true")) { getRegistersFromSvcdump(); return; } /* * Try and get the registers from the following locations: * * 1) RTM2 work area * 2) BPXGMSTA service * 3) linkage stack entries * 4) TCB * 5) Usta * * if any succeeds we return otherwise move to the next location. */ int whereCount = 0; try { if ((regs = getRegistersFromRTM2()) != null && whereCount++ >= whereSkip) { whereFound = "RTM2"; failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } /* If we still have not found a dsa, invoke kernel svs */ try { if ((regs = getRegistersFromBPXGMSTA()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (whereFound == null) whereFound = "BPXGMSTA"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { //throw new Error("oops: " + e); } try { if ((regs = getRegistersFromLinkageStack()) != null && whereCount++ >= whereSkip) { whereFound = "Linkage"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "Cel4rreg","Unexepected exception", e); throw new Error("Unexpected IOException: " + e); } try { if ((regs = getRegistersFromTCB()) != null && whereCount++ >= whereSkip) { whereFound = "TCB"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } try { if (is64bit) { /* This is from celqrreg.plx370: "Get the save R4 from a NOSTACK call" */ long lca = CeexlaaTemplate.getCeelaa_lca64(inputStream, laa); p_dsaptr = CeelcaTemplate.getCeelca_savstack(inputStream, lca); log.fine("p_dsaptr from lca = " + hex(p_dsaptr)); p_dsafmt = stackdirection = CEECAASTACK_DOWN; if (validateDSA() == 0 && whereCount++ >= whereSkip) { whereFound = "LCA"; return; } } } catch (IOException e) { throw new Error("oops: " + e); } /* Last ditch */ try { if ((regs = getRegistersFromUsta()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { } whereFound = "not found"; } /** * Try and get the registers from the RTM2 work area. Returns null if none found. As a * side-effect it also sets the stackdirection. */ private RegisterSet getRegistersFromRTM2() throws IOException { int level = ceecaalevel(); log.finer("caa level is " + level); /* If the CAA level is 13 or greater, get stack direction from * CAA. For older releases or the dummy CAA, default stack * direction to UP. */ if (is64bit) { /* Always use downstack in 64-bit mode? */ stackdirection = CEECAASTACK_DOWN; log.finer("stack direction is down"); } else if (level >= 13) { /* If LE 2.10 or higher */ /* Obtain dsa format from the CAA */ stackdirection = ceecaa_stackdirection(); log.finer("stack direction is " + (stackdirection == CEECAASTACK_UP ? "up" : "down")); } else { stackdirection = CEECAASTACK_UP; log.finer("stack direction is up"); } if ((stackdirection == CEECAASTACK_DOWN) && !is64bit) { try { long tempptr = ceecaasmcb(); //the ceecaasmcb call is not currently supported for 64 bit CAAs seghigh = SmcbTemplate.getSmcb_dsbos(inputStream, tempptr); seglow = CeexstkhTemplate.getStkh_stackfloor(inputStream, seghigh); } catch (Exception e) { //throw new Error("oops: " + e); return null; } } /* At this point, a valid CAA has been obtained. Access the RTM2 to obtain the DSA. */ long rtm2ptr = tcb.tcbrtwa(); if (rtm2ptr != 0) { try { log.finer("found some rtm2 registers"); RegisterSet regs = new RegisterSet(); long rtm2grs = rtm2ptr + Ihartm2aTemplate.getRtm2ereg$offset(); long rtm2grshi = rtm2ptr + Ihartm2aTemplate.getRtm2g64h$offset(); for (int i = 0; i < 16; i++) { long low = space.readUnsignedInt(rtm2grs + i*4); long high = is64bit ? space.readUnsignedInt(rtm2grshi + i*4) : 0; regs.setRegister(i, (high << 32) | low); } long rtm2psw = rtm2ptr + Ihartm2aTemplate.getRtm2apsw$offset(); regs.setPSW(space.readLong(rtm2psw)); if (registersValid(regs)) { log.finer("found good dsa in rtm2"); } else { log.finer("bad dsa in rtm2"); regs = null; } return regs; } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } } else { log.finer("failed to get registers from rtm2"); return null; } } /** * Validates the given register set with retry for down stack */ private boolean registersValid(RegisterSet regs) throws IOException { if (regs == null) return false; p_dsafmt = stackdirection; if (p_dsafmt == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } int lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } else { if (stackdirection == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 (again) = " + hex(p_dsaptr)); p_dsafmt = CEECAASTACK_UP; lastrc = validateDSA(); if (lastrc == WARNING) { lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } } } /* reset values */ log.finer("p_dsaptr invalid so reset: " + hex(p_dsaptr)); p_dsaptr = 0; } return false; } /** * Try and get the registers from the BPXGMSTA service. */ private RegisterSet getRegistersFromBPXGMSTA() throws IOException { RegisterSet regs = tcb.getRegistersFromBPXGMSTA(); if (is64bit) // celqrreg appears to always assume down stack stackdirection = CEECAASTACK_DOWN; if (registersValid(regs)) { log.finer("found good dsa in BPXGMSTA"); return regs; } else { log.finer("BPX registers are invalid so keep looking"); return null; } } /** * Try and get the registers from the linkage stack. */ private RegisterSet getRegistersFromLinkageStack() throws IOException { log.finer("enter getRegistersFromLinkageStack"); try { Lse[] linkageStack = tcb.getLinkageStack(); /* If Linkage stack is empty, leave */ if (linkageStack.length == 0) { log.finer("empty linkage stack"); return null; } for (int i = 0; i < linkageStack.length; i++) { Lse lse = linkageStack[i]; if (lse.lses1pasn() == space.getAsid()) { RegisterSet regs = new RegisterSet(); if (lse.isZArchitecture() && (lse.lses1typ7() == Lse.LSED1PC || lse.lses1typ7() == Lse.LSED1BAKR)) { log.finer("found some z arch registers"); regs.setPSW(lse.lses1pswh()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lses1grs(j)); } } else { log.finer("found some non z arch registers"); regs.setPSW(lse.lsespsw()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lsesgrs(j)); } } if (registersValid(regs)) { log.finer("found good dsa in linkage stack"); return regs; } } else { log.finer("different asid: " + hex(lse.lses1pasn())); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } log.finer("could not find registers in linkage stack"); return null; } /** * Try and get the registers from the TCB. */ private RegisterSet getRegistersFromTCB() throws IOException { log.finer("getRegistersFromTCB"); RegisterSet regs = tcb.getRegisters(); if (registersValid(regs)) { log.finer("found good dsa in TCB"); return regs; } else { return null; } } /** * Try and get the registers from the Usta. Note that this is a kind of last-ditch * thing and so no validation is done. */ private RegisterSet getRegistersFromUsta() throws IOException { log.fine("enter getRegistersFromUsta"); RegisterSet regs = tcb.getRegistersFromUsta(); if (registersValid(regs)) { log.finer("found good dsa in Usta"); return regs; } else { /* If there are more than three stack entries that's probably better than nothing */ boolean isDownStack = stackdirection == CEECAASTACK_DOWN; long dsaptr; if (isDownStack) { dsaptr = regs.getRegister(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { dsaptr = regs.getRegister(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } try { DsaStackFrame dsa = new DsaStackFrame(dsaptr, isDownStack, regs, space, Caa.this); int count = 0; for (; dsa != null; dsa = dsa.getParentFrame()) { if (++count > 3) { p_dsaptr = dsaptr; p_dsafmt = stackdirection; return regs; } } } catch (IOException e) { } catch (AssertionError e) { } } return null; } /** * Try and get the registers using the old svcdump code. This is for debugging * purposes only. Uses reflection so there is no compilation dependency. */ private void getRegistersFromSvcdump() { } /** * Validate the given DSA. Returns 0 if valid. Note because this is Java, we can't * modify the input parameters, so we use the instance variables instead and * val_dsa == p_dsaptr, val_dsafmt == p_dsafmt. */ private int validateDSA() { log.finer("attempt to validate " + hex(p_dsaptr) + " on " + (p_dsafmt == CEECAASTACK_DOWN ? "down" : "up") + " stack"); try { if (is64bit) { assert laa != 0; long l_sancptr = CeexlaaTemplate.getCeelaa_sanc64(inputStream, laa); assert l_sancptr != 0; long seghigh = CeexsancTemplate.getSanc_bos(inputStream, l_sancptr); long seglow = 0; long sanc_stack = CeexsancTemplate.getSanc_stack(inputStream, l_sancptr); long sanc_user_stack = CeexsancTemplate.getSanc_user_stack(inputStream, l_sancptr); if (sanc_stack == sanc_user_stack) { /* Get Stackfloor from sanc */ seglow = CeexsancTemplate.getSanc_user_floor(inputStream, l_sancptr); } else { /* Get StackFloor from LAA */ seglow = CeexlaaTemplate.getCeelaa_stackfloor64(inputStream, laa); } if (p_dsaptr < seghigh && (p_dsaptr + 0x800) >= seglow && (p_dsaptr & 0xf) == 0) { log.finer("dsa " + hex(p_dsaptr) + " is within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return 0; } else { log.finer("dsa " + hex(p_dsaptr) + " is NOT within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return ERROR; } } if (p_dsafmt == CEECAASTACK_DOWN) { /* the check for being in the current segment is commented out */ } else { if (is64bit) return ERROR; long tptr = ceecaaerrcm(); /* Chicken egg situation */ //assert !space.is64bit(); /* If the input DSA address is within the HCOM and double word aligned, * assume that it is good. */ if (p_dsaptr < (tptr + hcomLength) && p_dsaptr >= tptr && (p_dsaptr & 7) == 0) { log.finer("upstack dsa " + hex(p_dsaptr) + " is inside hcom"); return 0; } } long ddsa = ceecaaddsa(); long dsaptr = p_dsaptr; int dsafmt8 = p_dsafmt; long slowdsaptr = p_dsaptr; int slowdsafmt8 = p_dsafmt; for (boolean slow = false;; slow = !slow) { Ceexdsaf dsaf = new Ceexdsaf(space, dsaptr, dsafmt8, is64bit); /* If the stack direction is down but we are validating an upstack DSA * and the current DSA is inside the current segment of the down stack, * assume this must be a OS_NOSTACK call, return WARNING and replace * input DSA and DSAFmt with R4 value from this DSA */ log.finer("looping with dsa = " + hex(dsaptr)); if (stackdirection == CEECAASTACK_DOWN && p_dsafmt == CEECAASTACK_UP && dsaptr < seghigh && dsaptr >= seglow) { p_dsaptr = CeedsaTemplate.getCeedsar4(inputStream, dsaptr); p_dsafmt = CEECAASTACK_DOWN; log.finer("warning, try switching to down stack"); return WARNING; } long callers_dsaptr = dsaf.DSA_Prev; dsafmt8 = dsaf.DSA_Format; /* If we are not able to backchain any farther or we have encountered * a linkage stack, assume that the input DSA address is bad. */ if (callers_dsaptr == 0 || callers_dsaptr == F1SA) { log.finer("cannot backchain futher because " + (callers_dsaptr == 0 ? "zero" : "linkage stack") + " found"); return ERROR; } /* If we were able to backchain to the dummy DSA, the input DSA address * must be good. */ if (callers_dsaptr == ddsa) { log.finer("dummy dsa reached"); return 0; } /* If we backchained across a stack transition, assume that the input * DSA address is good. */ if (dsafmt8 != p_dsafmt) { log.finer("backchained across a stack transition"); return 0; } /* If we have located an upstack DSA with a valid NAB value, assume that * the input DSA address is good. */ if (dsafmt8 == CEECAASTACK_UP) { long tptr = CeedsaTemplate.getCeedsanab(inputStream, callers_dsaptr); if (tptr == dsaptr) { log.finer("upstack DSA is good"); return 0; } } dsaptr = callers_dsaptr; /* We use the Tortoise and the Hare algorithm to detect loops. If the slow * iterator is lapped it means there is a loop. */ if (slow) { dsaf = new Ceexdsaf(space, slowdsaptr, slowdsafmt8, is64bit); slowdsaptr = dsaf.DSA_Prev; slowdsafmt8 = dsaf.DSA_Format; } if (dsaptr == slowdsaptr) { log.finer("loop detected in DSA chain"); return ERROR; } } } catch (IOException e) { /* Any bad read means the DSA was invalid */ log.logp(Level.FINER,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Bad read", e); return ERROR; } catch (Exception e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Unexepected exception", e); throw new Error("Unexpected Exception:: " + e); } } } |
blob | blob, long method | t | t | t | long method | 0 | 4492 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/corereaders/tdump/zebedee/le/Caa.java/#L348-L800 | 1 | 464 | 4492 | major | |
| 1885 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, blob | t | t | t | blob | 0 | 12293 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 1885 | 12293 | minor | |
| 4031 | { "response": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer388 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer388() {} public Customer388(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer388[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | blob, data class | t | t | t | blob | 0 | 10668 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer388.java/#L8-L27 | 1 | 4031 | 10668 | major | |
| 575 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplication of code 5. Inconsistent formatting and naming conventions 6. Violation of the single responsibility principle 7. Use of complex structures and data types in parameters 8. Inefficient use of variables and data structures 9. Inadequate error handling and input validation 10. Use of hard-coded or external resources without proper abstraction. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy3 Magic numbers4 Duplication of code5 Inconsistent formatting and naming conventions6 Violation of the single responsibility principle7 Use of complex structures and data types in parameters8 Inefficient use of variables and data structures9 Inadequate error handling and input validation | t | f | t | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 575 | 5777 | critical | ||
| 5498 | YES I found bad smells. The bad smells are: Long method. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
long method | Long method | t | f | t | 0 | 3000 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5498 | 3000 | critical | ||
| 2643 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | data class | t | t | t | 0 | 15147 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 2643 | 15147 | major | ||
| 2139 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ActionNamesAction extends ActionSupport { private static final long serialVersionUID = -5389385242431387840L; private Set actionNames; private String namespace = ""; private Set namespaces; private String extension; protected ConfigurationHelper configHelper; @Inject public void setConfigurationHelper(ConfigurationHelper cfg) { this.configHelper = cfg; } public Set getActionNames() { return actionNames; } public String getNamespace() { return StringEscapeUtils.escapeHtml4(namespace); } public void setNamespace(String namespace) { this.namespace = namespace; } @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION) public void setExtension(String ext) { this.extension = ext; } public ActionConfig getConfig(String actionName) { return configHelper.getActionConfig(namespace, actionName); } public Set getNamespaces() { return namespaces; } public String getExtension() { if (extension == null) { return "action"; } if (extension.contains(",")) { return extension.substring(0, extension.indexOf(",")); } return extension; } public String execute() throws Exception { namespaces = configHelper.getNamespaces(); if (namespaces.size() == 0) { addActionError("There are no namespaces in this configuration"); return ERROR; } if (namespace == null) { namespace = ""; } actionNames = new TreeSet(configHelper.getActionNames(namespace)); return SUCCESS; } /** * Index action to support cooperation with REST plugin * * @return action result * @throws Exception */ public String index() throws Exception { return execute(); } public String redirect() { return SUCCESS; } } |
data class | data class | t | t | t | 0 | 13262 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/config-browser/src/main/java/org/apache/struts2/config_browser/ActionNamesAction.java/#L33-L111 | 1 | 2139 | 13262 | major | ||
| 2062 | YES, I found bad smells 1. Conditional complexity 2. Duplicate code 3. Long method 4. Long parameter list 5. Primitive obsession 6. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | Conditional complexity2 Duplicate code 3 Long method 4 Long parameter list 5 Primitive obsession 6 Feature envy | t | f | t | 0 | 12975 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 2 | 2062 | 12975 | major | ||
| 2583 | { "message": "YES I found bad smells", "the bad smells are": [ "3. Feature Envy", "4. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | 3. feature envy, 4. long method | t | t | t | 3. feature envy | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2583 | 14963 | minor | |
| 2748 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Poor exception handling 4. Use of magic numbers 5. Lack of proper commenting/documentation 6. Unnecessary nesting in switch statement 7. Unnecessary use of mutable fields 8. Potential for memory leaks through use of mutable fields without proper resetting before return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy3 Poor exception handling4 Use of magic numbers5 Lack of proper commenting/documentation6 Unnecessary nesting in switch statement7 Unnecessary use of mutable fields 8 Potential for memory leaks through use of mutable fields without proper resetting before return statements | t | f | t | 0 | 804 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2748 | 804 | major | ||
| 3694 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8659 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 3694 | 8659 | minor | ||
| 3653 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | long method, data class | t | t | t | long method | 0 | 8313 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 3653 | 8313 | minor | |
| 1651 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11579 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 1651 | 11579 | minor | ||
| 1935 | {"message": "YES, I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InternalCacheBuilder { private static final Logger logger = LogService.getLogger(); private static final String USE_ASYNC_EVENT_LISTENERS_PROPERTY = GEMFIRE_PREFIX + "Cache.ASYNC_EVENT_LISTENERS"; private static final boolean IS_EXISTING_OK_DEFAULT = true; private static final boolean IS_CLIENT_DEFAULT = false; private final Properties configProperties; private final CacheConfig cacheConfig; private final CompositeMeterRegistryFactory compositeMeterRegistryFactory; private final Consumer metricsSessionInitializer; private final Supplier singletonSystemSupplier; private final Supplier singletonCacheSupplier; private final InternalDistributedSystemConstructor internalDistributedSystemConstructor; private final InternalCacheConstructor internalCacheConstructor; private boolean isExistingOk = IS_EXISTING_OK_DEFAULT; private boolean isClient = IS_CLIENT_DEFAULT; /** * Setting useAsyncEventListeners to true will invoke event listeners in asynchronously. * * * Default is specified by system property {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ private boolean useAsyncEventListeners = Boolean.getBoolean(USE_ASYNC_EVENT_LISTENERS_PROPERTY); private PoolFactory poolFactory; private TypeRegistry typeRegistry; /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder() { this(new Properties(), new CacheConfig()); } /** * Create a cache factory initialized with the given configuration properties. For a list of valid * configuration properties and their meanings see {@link ConfigurationProperties}. * * @param configProperties the configuration properties to initialize the factory with. */ public InternalCacheBuilder(Properties configProperties) { this(configProperties == null ? new Properties() : configProperties, new CacheConfig()); } /** * Creates a cache factory with default configuration properties. */ public InternalCacheBuilder(CacheConfig cacheConfig) { this(new Properties(), cacheConfig); } private InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig) { this(configProperties, cacheConfig, new CacheMeterRegistryFactory(), CacheLifecycleMetricsSession.builder()::build, InternalDistributedSystem::getConnectedInstance, InternalDistributedSystem::connectInternal, GemFireCacheImpl::getInstance, GemFireCacheImpl::new); } @VisibleForTesting InternalCacheBuilder(Properties configProperties, CacheConfig cacheConfig, CompositeMeterRegistryFactory compositeMeterRegistryFactory, Consumer metricsSessionInitializer, Supplier singletonSystemSupplier, InternalDistributedSystemConstructor internalDistributedSystemConstructor, Supplier singletonCacheSupplier, InternalCacheConstructor internalCacheConstructor) { this.configProperties = configProperties; this.cacheConfig = cacheConfig; this.compositeMeterRegistryFactory = compositeMeterRegistryFactory; this.metricsSessionInitializer = metricsSessionInitializer; this.singletonSystemSupplier = singletonSystemSupplier; this.internalDistributedSystemConstructor = internalDistributedSystemConstructor; this.internalCacheConstructor = internalCacheConstructor; this.singletonCacheSupplier = singletonCacheSupplier; } /** * @see CacheFactory#create() * * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). * @throws IllegalStateException if cache already exists and is not compatible with the new * configuration. * @throws AuthenticationFailedException if authentication fails. * @throws AuthenticationRequiredException if the distributed system is in secure mode and this * new member is not configured with security credentials. */ public InternalCache create() throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { synchronized (InternalCacheBuilder.class) { InternalDistributedSystem internalDistributedSystem = findInternalDistributedSystem() .orElseGet(() -> createInternalDistributedSystem()); return create(internalDistributedSystem); } } /** * @see CacheFactory#create(DistributedSystem) * * @throws IllegalArgumentException If {@code system} is not {@link DistributedSystem#isConnected * connected}. * @throws CacheExistsException If an open cache already exists. * @throws CacheXmlException If a problem occurs while parsing the declarative caching XML file. * @throws TimeoutException If a {@link Region#put(Object, Object)} times out while initializing * the cache. * @throws CacheWriterException If a {@code CacheWriterException} is thrown while initializing the * cache. * @throws GatewayException If a {@code GatewayException} is thrown while initializing the cache. * @throws RegionExistsException If the declarative caching XML file describes a region that * already exists (including the root region). */ public InternalCache create(InternalDistributedSystem internalDistributedSystem) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { requireNonNull(internalDistributedSystem, "internalDistributedSystem"); try { synchronized (InternalCacheBuilder.class) { synchronized (GemFireCacheImpl.class) { InternalCache cache = existingCache(internalDistributedSystem::getCache, singletonCacheSupplier); if (cache == null) { int systemId = internalDistributedSystem.getConfig().getDistributedSystemId(); String memberName = internalDistributedSystem.getName(); String hostName = internalDistributedSystem.getDistributedMember().getHost(); CompositeMeterRegistry compositeMeterRegistry = compositeMeterRegistryFactory .create(systemId, memberName, hostName); metricsSessionInitializer.accept(compositeMeterRegistry); cache = internalCacheConstructor.construct(isClient, poolFactory, internalDistributedSystem, cacheConfig, useAsyncEventListeners, typeRegistry, compositeMeterRegistry); internalDistributedSystem.setCache(cache); cache.initialize(); } else { internalDistributedSystem.setCache(cache); } return cache; } } } catch (CacheXmlException | IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw e; } catch (Error | RuntimeException e) { logger.error(e); throw e; } } /** * @see CacheFactory#set(String, String) */ public InternalCacheBuilder set(String name, String value) { configProperties.setProperty(name, value); return this; } /** * @see CacheFactory#setPdxReadSerialized(boolean) */ public InternalCacheBuilder setPdxReadSerialized(boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * @see CacheFactory#setSecurityManager(SecurityManager) */ public InternalCacheBuilder setSecurityManager(SecurityManager securityManager) { cacheConfig.setSecurityManager(securityManager); return this; } /** * @see CacheFactory#setPostProcessor(PostProcessor) */ public InternalCacheBuilder setPostProcessor(PostProcessor postProcessor) { cacheConfig.setPostProcessor(postProcessor); return this; } /** * @see CacheFactory#setPdxSerializer(PdxSerializer) */ public InternalCacheBuilder setPdxSerializer(PdxSerializer serializer) { cacheConfig.setPdxSerializer(serializer); return this; } /** * @see CacheFactory#setPdxDiskStore(String) */ public InternalCacheBuilder setPdxDiskStore(String diskStoreName) { cacheConfig.setPdxDiskStore(diskStoreName); return this; } /** * @see CacheFactory#setPdxPersistent(boolean) */ public InternalCacheBuilder setPdxPersistent(boolean isPersistent) { cacheConfig.setPdxPersistent(isPersistent); return this; } /** * @see CacheFactory#setPdxIgnoreUnreadFields(boolean) */ public InternalCacheBuilder setPdxIgnoreUnreadFields(boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } public InternalCacheBuilder setCacheXMLDescription(String cacheXML) { if (cacheXML != null) { cacheConfig.setCacheXMLDescription(cacheXML); } return this; } /** * @param isExistingOk default is true. */ public InternalCacheBuilder setIsExistingOk(boolean isExistingOk) { this.isExistingOk = isExistingOk; return this; } /** * @param isClient default is false. */ public InternalCacheBuilder setIsClient(boolean isClient) { this.isClient = isClient; return this; } /** * @param useAsyncEventListeners default is specified by the system property * {@code gemfire.Cache.ASYNC_EVENT_LISTENERS}. */ public InternalCacheBuilder setUseAsyncEventListeners(boolean useAsyncEventListeners) { this.useAsyncEventListeners = useAsyncEventListeners; return this; } /** * @param poolFactory default is null. */ public InternalCacheBuilder setPoolFactory(PoolFactory poolFactory) { this.poolFactory = poolFactory; return this; } /** * @param typeRegistry default is null. */ public InternalCacheBuilder setTypeRegistry(TypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; return this; } private Optional findInternalDistributedSystem() { InternalDistributedSystem internalDistributedSystem = null; if (configProperties.isEmpty() && !ALLOW_MULTIPLE_SYSTEMS) { // any ds will do internalDistributedSystem = singletonSystemSupplier.get(); validateUsabilityOfSecurityCallbacks(internalDistributedSystem, cacheConfig); } return Optional.ofNullable(internalDistributedSystem); } private InternalDistributedSystem createInternalDistributedSystem() { SecurityConfig securityConfig = new SecurityConfig( cacheConfig.getSecurityManager(), cacheConfig.getPostProcessor()); return internalDistributedSystemConstructor.construct(configProperties, securityConfig); } private InternalCache existingCache(Supplier systemCacheSupplier, Supplier singletonCacheSupplier) { InternalCache cache = ALLOW_MULTIPLE_SYSTEMS ? systemCacheSupplier.get() : singletonCacheSupplier.get(); if (validateExistingCache(cache)) { return cache; } return null; } /** * Validates that isExistingOk is true and existing cache is compatible with cacheConfig. * * if instance exists and cacheConfig is incompatible * if instance exists and isExistingOk is false */ private boolean validateExistingCache(InternalCache existingCache) { if (existingCache == null || existingCache.isClosed()) { return false; } if (isExistingOk) { cacheConfig.validateCacheConfig(existingCache); } else { existingCache.throwCacheExistsException(); } return true; } /** * if existing DistributedSystem connection cannot use specified SecurityManager or * PostProcessor. */ private static void validateUsabilityOfSecurityCallbacks( InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig) throws GemFireSecurityException { if (internalDistributedSystem == null) { return; } // pre-existing DistributedSystem already has an incompatible SecurityService in use if (cacheConfig.getSecurityManager() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified SecurityManager"); } if (cacheConfig.getPostProcessor() != null) { throw new GemFireSecurityException( "Existing DistributedSystem connection cannot use specified PostProcessor"); } } @VisibleForTesting interface InternalCacheConstructor { InternalCache construct(boolean isClient, PoolFactory poolFactory, InternalDistributedSystem internalDistributedSystem, CacheConfig cacheConfig, boolean useAsyncEventListeners, TypeRegistry typeRegistry, MeterRegistry meterRegistry); } @VisibleForTesting interface InternalDistributedSystemConstructor { InternalDistributedSystem construct(Properties configProperties, SecurityConfig securityConfig); } } |
blob | blob | t | t | t | 0 | 12464 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/InternalCacheBuilder.java/#L56-L420 | 1 | 1935 | 12464 | major | ||
| 2340 | YES, bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 2340 | 14174 | minor | ||
| 139 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GroupMultiplicitiesElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.validation.ConcreteSyntaxValidationTestLanguage.GroupMultiplicities"); private final Group cGroup = (Group)rule.eContents().get(1); private final Keyword cNumberSignDigitFourKeyword_0 = (Keyword)cGroup.eContents().get(0); private final Assignment cVal1Assignment_1 = (Assignment)cGroup.eContents().get(1); private final RuleCall cVal1IDTerminalRuleCall_1_0 = (RuleCall)cVal1Assignment_1.eContents().get(0); private final Keyword cKw1Keyword_2 = (Keyword)cGroup.eContents().get(2); private final Group cGroup_3 = (Group)cGroup.eContents().get(3); private final Assignment cVal2Assignment_3_0 = (Assignment)cGroup_3.eContents().get(0); private final RuleCall cVal2IDTerminalRuleCall_3_0_0 = (RuleCall)cVal2Assignment_3_0.eContents().get(0); private final Assignment cVal3Assignment_3_1 = (Assignment)cGroup_3.eContents().get(1); private final RuleCall cVal3IDTerminalRuleCall_3_1_0 = (RuleCall)cVal3Assignment_3_1.eContents().get(0); private final Keyword cKw2Keyword_4 = (Keyword)cGroup.eContents().get(4); private final Group cGroup_5 = (Group)cGroup.eContents().get(5); private final Assignment cVal4Assignment_5_0 = (Assignment)cGroup_5.eContents().get(0); private final RuleCall cVal4IDTerminalRuleCall_5_0_0 = (RuleCall)cVal4Assignment_5_0.eContents().get(0); private final Assignment cVal5Assignment_5_1 = (Assignment)cGroup_5.eContents().get(1); private final RuleCall cVal5IDTerminalRuleCall_5_1_0 = (RuleCall)cVal5Assignment_5_1.eContents().get(0); private final Keyword cKw3Keyword_6 = (Keyword)cGroup.eContents().get(6); private final Group cGroup_7 = (Group)cGroup.eContents().get(7); private final Assignment cVal6Assignment_7_0 = (Assignment)cGroup_7.eContents().get(0); private final RuleCall cVal6IDTerminalRuleCall_7_0_0 = (RuleCall)cVal6Assignment_7_0.eContents().get(0); private final Assignment cVal7Assignment_7_1 = (Assignment)cGroup_7.eContents().get(1); private final RuleCall cVal7IDTerminalRuleCall_7_1_0 = (RuleCall)cVal7Assignment_7_1.eContents().get(0); //GroupMultiplicities: // "#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)*; @Override public ParserRule getRule() { return rule; } //"#4" val1=ID "kw1" (val2=ID val3=ID)? "kw2" (val4+=ID val5+=ID)+ "kw3" (val6+=ID val7+=ID)* public Group getGroup() { return cGroup; } //"#4" public Keyword getNumberSignDigitFourKeyword_0() { return cNumberSignDigitFourKeyword_0; } //val1=ID public Assignment getVal1Assignment_1() { return cVal1Assignment_1; } //ID public RuleCall getVal1IDTerminalRuleCall_1_0() { return cVal1IDTerminalRuleCall_1_0; } //"kw1" public Keyword getKw1Keyword_2() { return cKw1Keyword_2; } //(val2=ID val3=ID)? public Group getGroup_3() { return cGroup_3; } //val2=ID public Assignment getVal2Assignment_3_0() { return cVal2Assignment_3_0; } //ID public RuleCall getVal2IDTerminalRuleCall_3_0_0() { return cVal2IDTerminalRuleCall_3_0_0; } //val3=ID public Assignment getVal3Assignment_3_1() { return cVal3Assignment_3_1; } //ID public RuleCall getVal3IDTerminalRuleCall_3_1_0() { return cVal3IDTerminalRuleCall_3_1_0; } //"kw2" public Keyword getKw2Keyword_4() { return cKw2Keyword_4; } //(val4+=ID val5+=ID)+ public Group getGroup_5() { return cGroup_5; } //val4+=ID public Assignment getVal4Assignment_5_0() { return cVal4Assignment_5_0; } //ID public RuleCall getVal4IDTerminalRuleCall_5_0_0() { return cVal4IDTerminalRuleCall_5_0_0; } //val5+=ID public Assignment getVal5Assignment_5_1() { return cVal5Assignment_5_1; } //ID public RuleCall getVal5IDTerminalRuleCall_5_1_0() { return cVal5IDTerminalRuleCall_5_1_0; } //"kw3" public Keyword getKw3Keyword_6() { return cKw3Keyword_6; } //(val6+=ID val7+=ID)* public Group getGroup_7() { return cGroup_7; } //val6+=ID public Assignment getVal6Assignment_7_0() { return cVal6Assignment_7_0; } //ID public RuleCall getVal6IDTerminalRuleCall_7_0_0() { return cVal6IDTerminalRuleCall_7_0_0; } //val7+=ID public Assignment getVal7Assignment_7_1() { return cVal7Assignment_7_1; } //ID public RuleCall getVal7IDTerminalRuleCall_7_1_0() { return cVal7IDTerminalRuleCall_7_1_0; } } |
data class | data class, long method | t | t | t | long method | 0 | 1751 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/services/ConcreteSyntaxValidationTestLanguageGrammarAccess.java/#L414-L508 | 1 | 139 | 1751 | minor | |
| 2230 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
data class | data class, long method | t | t | t | long method | 0 | 13584 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 2230 | 13584 | minor | |
| 922 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | Long method | t | f | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 922 | 8279 | minor | ||
| 598 | YES I found bad smells the bad smells are: 1. Long Method 2. Long Parameter List | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long Method2 Long Parameter List | t | f | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 598 | 5982 | major | ||
| 693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Poor exception handling 5. Mixing of concerns 6. Inconsistent naming conventions 7. Immodular code 8. Unnecessary commented out code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method2 Feature envy3 Duplicate code4 Poor exception handling5 Mixing of concerns 6 Inconsistent naming conventions 7 Immodular code8 Unnecessary commented out code | t | f | t | 0 | 6654 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 693 | 6654 | major | ||
| 1811 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | Data Class | t | f | t | 0 | 12061 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 1811 | 12061 | minor | ||
| 706 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | 1. data class | t | t | t | 0 | 6735 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 706 | 6735 | minor | ||
| 3412 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 1 | 3412 | 6662 | minor | ||
| 956 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
long method | 1. long method | t | t | t | 0 | 8539 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 1 | 956 | 8539 | minor | ||
| 620 | YES I found bad smells. the bad smells are: long method, feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, feature envy | t | f | t | feature envy. | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 620 | 6215 | minor | |
| 883 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | long method | t | t | t | 0 | 8029 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 883 | 8029 | minor | ||
| 1486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 1486 | 11092 | major | ||
| 393 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | long method | t | t | t | 0 | 3969 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 393 | 3969 | major | ||
| 3889 | YES, I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void addRequiredAlertProperties(Set properties) { properties.add(AlertResourceProvider.ALERT_STATE); properties.add(AlertResourceProvider.ALERT_ORIGINAL_TIMESTAMP); properties.add(AlertResourceProvider.ALERT_MAINTENANCE_STATE); } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 10168 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/api/query/render/AlertSummaryRenderer.java/#L205-L209 | 2 | 3889 | 10168 | critical | |
| 543 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 5544 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 2 | 543 | 5544 | minor | |
| 1221 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10334 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 1221 | 10334 | major | |
| 46 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public UDATA add(UDATA parameter) { return new UDATA(this).add(parameter); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 835 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/types/U32.java/#L70-L72 | 2 | 46 | 835 | minor | |
| 1194 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | long method | t | t | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 1 | 1194 | 10265 | minor | ||
| 859 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | long method | t | t | t | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 1 | 859 | 7898 | minor | ||
| 867 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private String omServiceId; private String omNodeId; private InetSocketAddress rpcAddress; private int rpcPort; private int ratisPort; public Builder setRpcAddress(InetSocketAddress rpcAddr) { this.rpcAddress = rpcAddr; this.rpcPort = rpcAddress.getPort(); return this; } public Builder setRatisPort(int port) { this.ratisPort = port; return this; } public Builder setOMServiceId(String serviceId) { this.omServiceId = serviceId; return this; } public Builder setOMNodeId(String nodeId) { this.omNodeId = nodeId; return this; } public OMNodeDetails build() { return new OMNodeDetails(omServiceId, omNodeId, rpcAddress, rpcPort, ratisPort); } } |
data class | long method, data class | t | t | t | long method | 0 | 7941 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMNodeDetails.java/#L50-L82 | 1 | 867 | 7941 | minor | |
| 1044 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple lines creating and setting preferred feature rendering modes) 4. Magic numbers (hard-coded values for viewpoint locations and durations) 5. Hard-coded URLs for service feature tables 6. Nested if statements with no descriptive comments 7. Use of double && in conditional statements instead of using nested if/else statements 8. Use of arrays to add operational layers instead of using a more efficient data structure such as a list 9. Catch-all exception handling with no specific exception types included 10. Lack of error handling or validation for user input or potential errors in code 11. Lack of meaningful variable names (e.g. mapViewTop, mapViewBottom) 12. Use of mutable public fields instead of private fields with getters and setters 13. Multi-purpose method with no clear separation of concerns or functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
feature envy | Long method2 Feature envy3 Duplicate code (multiple lines creating and setting preferred feature rendering modes)4 Magic numbers (hard-coded values for viewpoint locations and durations)5 Hard-coded URLs for service feature tables6 Nested if statements with no descriptive comments 7 Use of double && in conditional statements instead of using nested if/else statements 8 Use of arrays to add operational layers instead of using a more efficient data structure such as a list 9 Catch-all exception handling with no specific exception types included | t | f | t | 0 | 9447 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1044 | 9447 | major | ||
| 4334 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | data class, long method | t | t | t | data class | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 4334 | 11444 | minor | |
| 2346 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | 1. data class | t | t | t | 0 | 14193 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 1 | 2346 | 14193 | major | ||
| 2001 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 2001 | 12710 | major | ||
| 542 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5540 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 542 | 5540 | minor | ||
| 766 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | long method | t | t | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 1 | 766 | 7185 | major | ||
| 4034 | Yes I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10674 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 4034 | 10674 | major | ||
| 948 | {"response": "YES I found bad smells\nthe bad smells are: 1. Blob, 2. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 8508 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 948 | 8508 | minor | |
| 490 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method | t | f | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 490 | 4881 | major | ||
| 5090 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | data class | t | t | t | 0 | 14228 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 1 | 5090 | 14228 | major | ||
| 700 | * * @param token * @param experiment * @return String * @throws RegistryServiceException */ YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6687 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 700 | 6687 | major | ||
| 1245 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | blob, data class | t | t | t | blob | 0 | 10419 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 1245 | 10419 | critical | |
| 1592 | YES I found bad smells the bad smells are: 1.Long method, 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
long method | Long method, 2Duplicated Code, 3Complex method, 4Long parameter list, 5Magic numbers, 6Inappropriate comments | t | f | t | 2.Duplicated Code, 3.Complex method, 4.Long parameter list, 5.Magic numbers, 6.Inappropriate comments. | 0 | 11396 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 2 | 1592 | 11396 | minor | |
| 2015 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2015 | 12768 | minor | ||
| 486 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4755 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 486 | 4755 | minor | ||
| 287 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
long method | Long method | t | f | t | 0 | 3060 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 287 | 3060 | minor | ||
| 1197 | YES, I found bad smells. The bad smells are: 1. Long method 2. Repeating code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Repeating code3 Feature envy | t | f | t | 0 | 10271 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1197 | 10271 | critical | ||
| 3786 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | long method | t | t | t | 0 | 9536 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 3786 | 9536 | minor | ||
| 2181 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | long method, data class | t | t | t | long method | 0 | 13416 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 1 | 2181 | 13416 | minor | |
| 143 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | data class, long method | t | t | t | long method | 0 | 1786 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 143 | 1786 | major | |
| 1928 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 12445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 1928 | 12445 | major | |
| 483 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | long method | t | t | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 483 | 4713 | minor | ||
| 2037 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Lack of comments/documentation 6. Inadequate naming convention 7. Use of raw types 8. Inconsistent formatting/indentation 9. unnecessary temporary variables 10. Empty catch blocks 11. Inconsistent use of logging 12. Use of non-descriptive/misleading variable names 13. Use of wildcard imports 14. Excessive and unnecessary nesting 15. Lack of error handling/exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Magic numbers 5 Lack of comments/documentation 6 Inadequate naming convention 7 Use of raw types 8 Inconsistent formatting/indentation 9 unnecessary temporary variables | t | f | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 2037 | 12838 | minor | ||
| 1837 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NormalizeResultSetNode(ResultSetNode chldRes, ResultColumnList targetResultColumnList, Properties tableProperties, boolean forUpdate, ContextManager cm) throws StandardException { super(chldRes, tableProperties, cm); this.forUpdate = forUpdate; ResultColumnList rcl = chldRes.getResultColumns(); ResultColumnList targetRCL = targetResultColumnList; /* We get a shallow copy of the ResultColumnList and its * ResultColumns. (Copy maintains ResultColumn.expression for now.) * * Setting this.resultColumns to the modified child result column list, * and making a new copy for the child result set node * ensures that the ProjectRestrictNode restrictions still points to * the same list. See d3494_npe_writeup-4.html in DERBY-3494 for a * detailed explanation of how this works. */ ResultColumnList prRCList = rcl; chldRes.setResultColumns(rcl.copyListAndObjects()); // Remove any columns that were generated. prRCList.removeGeneratedGroupingColumns(); // And also columns that were added for ORDER BY (DERBY-6006). prRCList.removeOrderByColumns(); /* Replace ResultColumn.expression with new VirtualColumnNodes * in the NormalizeResultSetNode's ResultColumnList. (VirtualColumnNodes include * pointers to source ResultSetNode, rsn, and source ResultColumn.) */ prRCList.genVirtualColumnNodes(chldRes, chldRes.getResultColumns()); setResultColumns( prRCList ); // Propagate the referenced table map if it's already been created if (chldRes.getReferencedTableMap() != null) { setReferencedTableMap((JBitSet) getReferencedTableMap().clone()); } if (targetResultColumnList != null) { int size = Math.min(targetRCL.size(), getResultColumns().size()); for (int index = 0; index < size; index++) { ResultColumn sourceRC = getResultColumns().elementAt(index); ResultColumn resultColumn = targetRCL.elementAt(index); sourceRC.setType(resultColumn.getTypeServices()); } } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12142 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/NormalizeResultSetNode.java/#L561-L612 | 1 | 1837 | 12142 | minor | |
| 2182 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | data class | t | t | t | 0 | 13420 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 2182 | 13420 | major | ||
| 120 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | data class | t | t | t | 0 | 1519 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 120 | 1519 | major | ||
| 86 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 1216 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 2 | 86 | 1216 | minor | ||
| 908 | YES I found bad smells. The bad smells are: Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Feature envy, Long method, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements | t | f | t | Feature envy, Magic numbers, Duplicate code, Inconsistent formatting, Primitive obsession, Data clumps, Cyclic complexity, and Too many return statements. | 0 | 8202 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 908 | 8202 | minor | |
| 1999 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 1999 | 12705 | major | |
| 1836 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | Long Method | t | f | t | 0 | 12140 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 1836 | 12140 | major | ||
| 495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | long method | t | t | t | 0 | 5014 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 495 | 5014 | minor | ||
| 5570 | YES I found bad smells The bad smells are: 1. Long method 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | Long method2Feature envy | t | f | t | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5570 | 8187 | minor | ||
| 3818 | YES, I found bad smells. The bad smells are: 1. Long method 2. Data class 3. Data clumps 4. Feature envy 5. Primitive obsession 6. Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NodeAnnounceMessage extends PacketImpl { protected String nodeID; protected String backupGroupName; protected boolean backup; protected long currentEventID; protected TransportConfiguration connector; protected TransportConfiguration backupConnector; private String scaleDownGroupName; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public NodeAnnounceMessage(final long currentEventID, final String nodeID, final String backupGroupName, final String scaleDownGroupName, final boolean backup, final TransportConfiguration tc, final TransportConfiguration backupConnector) { super(NODE_ANNOUNCE); this.currentEventID = currentEventID; this.nodeID = nodeID; this.backupGroupName = backupGroupName; this.backup = backup; this.connector = tc; this.backupConnector = backupConnector; this.scaleDownGroupName = scaleDownGroupName; } public NodeAnnounceMessage() { super(NODE_ANNOUNCE); } public NodeAnnounceMessage(byte nodeAnnounceMessage_V2) { super(nodeAnnounceMessage_V2); } // Public -------------------------------------------------------- public String getNodeID() { return nodeID; } public String getBackupGroupName() { return backupGroupName; } public boolean isBackup() { return backup; } public TransportConfiguration getConnector() { return connector; } public TransportConfiguration getBackupConnector() { return backupConnector; } public String getScaleDownGroupName() { return scaleDownGroupName; } /** * @return the currentEventID */ public long getCurrentEventID() { return currentEventID; } @Override public void encodeRest(final ActiveMQBuffer buffer) { buffer.writeString(nodeID); buffer.writeNullableString(backupGroupName); buffer.writeBoolean(backup); buffer.writeLong(currentEventID); if (connector != null) { buffer.writeBoolean(true); connector.encode(buffer); } else { buffer.writeBoolean(false); } if (backupConnector != null) { buffer.writeBoolean(true); backupConnector.encode(buffer); } else { buffer.writeBoolean(false); } buffer.writeNullableString(scaleDownGroupName); } @Override public void decodeRest(final ActiveMQBuffer buffer) { this.nodeID = buffer.readString(); this.backupGroupName = buffer.readNullableString(); this.backup = buffer.readBoolean(); this.currentEventID = buffer.readLong(); if (buffer.readBoolean()) { connector = new TransportConfiguration(); connector.decode(buffer); } if (buffer.readBoolean()) { backupConnector = new TransportConfiguration(); backupConnector.decode(buffer); } scaleDownGroupName = buffer.readNullableString(); } @Override public String toString() { return "NodeAnnounceMessage [backup=" + backup + ", connector=" + connector + ", nodeID=" + nodeID + ", toString()=" + super.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (backup ? 1231 : 1237); result = prime * result + ((backupConnector == null) ? 0 : backupConnector.hashCode()); result = prime * result + ((connector == null) ? 0 : connector.hashCode()); result = prime * result + (int) (currentEventID ^ (currentEventID >>> 32)); result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); result = prime * result + ((scaleDownGroupName == null) ? 0 : scaleDownGroupName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof NodeAnnounceMessage)) { return false; } NodeAnnounceMessage other = (NodeAnnounceMessage) obj; if (backup != other.backup) { return false; } if (backupConnector == null) { if (other.backupConnector != null) { return false; } } else if (!backupConnector.equals(other.backupConnector)) { return false; } if (connector == null) { if (other.connector != null) { return false; } } else if (!connector.equals(other.connector)) { return false; } if (currentEventID != other.currentEventID) { return false; } if (nodeID == null) { if (other.nodeID != null) { return false; } } else if (!nodeID.equals(other.nodeID)) { return false; } else if (!scaleDownGroupName.equals(other.scaleDownGroupName)) { return false; } return true; } } |
data class | Long method2 Data class3 Data clumps4 Feature envy5 Primitive obsession6 Message chains | t | f | t | 0 | 9732 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/NodeAnnounceMessage.java/#L23-L214 | 2 | 3818 | 9732 | minor | ||
| 804 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 7620 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 804 | 7620 | minor | ||
| 1965 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SignatureSupportingConfigProperties { private String sharedSecret; private String keyPath; private long tokenExpirationSeconds = 600L; private String certificatePath; /** * Gets the secret used for creating and validating HmacSHA256 based signatures. * * @return The secret or {@code null} if not set. */ public final String getSharedSecret() { return sharedSecret; } /** * Sets the secret to use for creating and validating HmacSHA256 based signatures. * * @param secret The shared secret. * @throws NullPointerException if secret is {@code null}. * @throws IllegalArgumentException if the secret is < 32 bytes. */ public final void setSharedSecret(final String secret) { if (Objects.requireNonNull(secret).getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalArgumentException("shared secret must be at least 32 bytes"); } this.sharedSecret = secret; } /** * Sets the path to the file containing the private key to be used * for creating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param keyPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setKeyPath(final String keyPath) { this.keyPath = Objects.requireNonNull(keyPath); } /** * Gets the path to the file containing the private key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getKeyPath() { return keyPath; } /** * Gets the period of time after which tokens created using this configuration should expire. * * @return The number of seconds after which tokens expire. */ public final long getTokenExpiration() { return tokenExpirationSeconds; } /** * Sets the period of time after which tokens created using this configuration should expire. * * The default value is 600 seconds (10 minutes). * * @param seconds The number of seconds after which tokens expire. * @throws IllegalArgumentException if seconds is <= 0. */ public final void setTokenExpiration(final long seconds) { if (seconds <= 0) { throw new IllegalArgumentException("token expiration must be > 0"); } this.tokenExpirationSeconds = seconds; } /** * Sets the path to the X.509 certificate containing the public key to be used * for validating SHA256withRSA based signatures. * * The file must be in PKCS8 PEM format. * * @param certPath The path to the PEM file. * @throws NullPointerException if the path is {@code null}. */ public final void setCertPath(final String certPath) { this.certificatePath = Objects.requireNonNull(certPath); } /** * Gets the path to the X.509 certificate containing the public key to be used * for validating RSA based signatures. * * @return The path to the file or {@code null} if not set. */ public final String getCertPath() { return certificatePath; } /** * Checks if this configuration contains enough information for creating assertions. * * @return {@code true} if any of sharedSecret or keyPath is not {@code null}. */ public final boolean isAppropriateForCreating() { return sharedSecret != null || keyPath != null; } /** * Checks if this configuration contains enough information for validating assertions. * * @return {@code true} if any of sharedSecret or certificatePath is not {@code null}. */ public final boolean isAppropriateForValidating() { return sharedSecret != null || certificatePath != null; } } |
data class | data class, long method | t | t | t | long method | 0 | 12591 | https://github.com/eclipse/hono/blob/ec84947227564c6459801f708bdeabd7687a8bf0/core/src/main/java/org/eclipse/hono/config/SignatureSupportingConfigProperties.java/#L22-L139 | 1 | 1965 | 12591 | major | |
| 947 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _Repository4Soap_QueryPendingSetsWithLocalWorkspaces implements ElementSerializable { // No attributes // Elements protected String localWorkspaceName; protected String localWorkspaceOwner; protected String queryWorkspaceName; protected String ownerName; protected _ItemSpec[] itemSpecs; protected boolean generateDownloadUrls; protected String[] itemPropertyFilters; public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces() { super(); } public _Repository4Soap_QueryPendingSetsWithLocalWorkspaces( final String localWorkspaceName, final String localWorkspaceOwner, final String queryWorkspaceName, final String ownerName, final _ItemSpec[] itemSpecs, final boolean generateDownloadUrls, final String[] itemPropertyFilters) { // TODO : Call super() instead of setting all fields directly? setLocalWorkspaceName(localWorkspaceName); setLocalWorkspaceOwner(localWorkspaceOwner); setQueryWorkspaceName(queryWorkspaceName); setOwnerName(ownerName); setItemSpecs(itemSpecs); setGenerateDownloadUrls(generateDownloadUrls); setItemPropertyFilters(itemPropertyFilters); } public String getLocalWorkspaceName() { return this.localWorkspaceName; } public void setLocalWorkspaceName(String value) { this.localWorkspaceName = value; } public String getLocalWorkspaceOwner() { return this.localWorkspaceOwner; } public void setLocalWorkspaceOwner(String value) { this.localWorkspaceOwner = value; } public String getQueryWorkspaceName() { return this.queryWorkspaceName; } public void setQueryWorkspaceName(String value) { this.queryWorkspaceName = value; } public String getOwnerName() { return this.ownerName; } public void setOwnerName(String value) { this.ownerName = value; } public _ItemSpec[] getItemSpecs() { return this.itemSpecs; } public void setItemSpecs(_ItemSpec[] value) { this.itemSpecs = value; } public boolean isGenerateDownloadUrls() { return this.generateDownloadUrls; } public void setGenerateDownloadUrls(boolean value) { this.generateDownloadUrls = value; } public String[] getItemPropertyFilters() { return this.itemPropertyFilters; } public void setItemPropertyFilters(String[] value) { this.itemPropertyFilters = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "localWorkspaceName", this.localWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "localWorkspaceOwner", this.localWorkspaceOwner); XMLStreamWriterHelper.writeElement( writer, "queryWorkspaceName", this.queryWorkspaceName); XMLStreamWriterHelper.writeElement( writer, "ownerName", this.ownerName); if (this.itemSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("itemSpecs"); for (int iterator0 = 0; iterator0 < this.itemSpecs.length; iterator0++) { this.itemSpecs[iterator0].writeAsElement( writer, "ItemSpec"); } writer.writeEndElement(); } XMLStreamWriterHelper.writeElement( writer, "generateDownloadUrls", this.generateDownloadUrls); if (this.itemPropertyFilters != null) { /* * The element type is an array. */ writer.writeStartElement("itemPropertyFilters"); for (int iterator0 = 0; iterator0 < this.itemPropertyFilters.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.itemPropertyFilters[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 8507 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_Repository4Soap_QueryPendingSetsWithLocalWorkspaces.java/#L33-L208 | 1 | 947 | 8507 | major | |
| 231 | { "message": "YES I found bad smells", "bad smells are": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CrunchInputFormat extends InputFormat { @Override public List getSplits(JobContext job) throws IOException, InterruptedException { List splits = Lists.newArrayList(); Configuration base = job.getConfiguration(); Map>> formatNodeMap = CrunchInputs.getFormatNodeMap(job); // First, build a map of InputFormats to Paths for (Map.Entry>> entry : formatNodeMap.entrySet()) { FormatBundle inputBundle = entry.getKey(); Configuration conf = new Configuration(base); inputBundle.configure(conf); Job jobCopy = new Job(conf); InputFormat format = (InputFormat) ReflectionUtils.newInstance(inputBundle.getFormatClass(), jobCopy.getConfiguration()); if (format instanceof FileInputFormat && !conf.getBoolean(RuntimeParameters.DISABLE_COMBINE_FILE, true)) { format = new CrunchCombineFileInputFormat(jobCopy); } for (Map.Entry> nodeEntry : entry.getValue().entrySet()) { Integer nodeIndex = nodeEntry.getKey(); List paths = nodeEntry.getValue(); FileInputFormat.setInputPaths(jobCopy, paths.toArray(new Path[paths.size()])); // Get splits for each input path and tag with InputFormat // and Mapper types by wrapping in a TaggedInputSplit. List pathSplits = format.getSplits(jobCopy); for (InputSplit pathSplit : pathSplits) { splits.add(new CrunchInputSplit(pathSplit, inputBundle, nodeIndex, jobCopy.getConfiguration())); } } } return splits; } @Override public RecordReader createRecordReader(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { return new CrunchRecordReader(inputSplit, context); } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 2520 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-core/src/main/java/org/apache/crunch/impl/mr/run/CrunchInputFormat.java/#L39-L79 | 1 | 231 | 2520 | minor | |
| 2368 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14301 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 2368 | 14301 | minor | ||
| 2053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 2 | 2053 | 12903 | minor | ||
| 2653 | return getCumulativeMemoryWithinPhase(join, YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15178 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2653 | 15178 | major | ||
| 136 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Duplicate code" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method, duplicate code | t | t | t | duplicate code | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 136 | 1673 | major | |
| 904 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method | t | t | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 904 | 8176 | minor | ||
| 2484 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ReportingService2005Soap_ValidateExtensionSettings implements ElementSerializable { // No attributes // Elements protected String extension; protected _ParameterValueOrFieldReference[] parameterValues; public _ReportingService2005Soap_ValidateExtensionSettings() { super(); } public _ReportingService2005Soap_ValidateExtensionSettings( final String extension, final _ParameterValueOrFieldReference[] parameterValues) { // TODO : Call super() instead of setting all fields directly? setExtension(extension); setParameterValues(parameterValues); } public String getExtension() { return this.extension; } public void setExtension(String value) { this.extension = value; } public _ParameterValueOrFieldReference[] getParameterValues() { return this.parameterValues; } public void setParameterValues(_ParameterValueOrFieldReference[] value) { this.parameterValues = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "Extension", this.extension); if (this.parameterValues != null) { /* * The element type is an array. */ writer.writeStartElement("ParameterValues"); for (int iterator0 = 0; iterator0 < this.parameterValues.length; iterator0++) { this.parameterValues[iterator0].writeAsElement( writer, "ParameterValueOrFieldReference"); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 14604 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ReportingService2005Soap_ValidateExtensionSettings.java/#L32-L107 | 1 | 2484 | 14604 | minor | ||
| 276 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method 2Feature envy | t | f | t | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 276 | 2964 | major | ||
| 1374 | YES, I found bad smellsThe bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10804 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 1374 | 10804 | major | ||
| 1739 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Duplicate code - the same code is repeated multiple times within the method. 4. Magic numbers - the values 1, 11, and 0 are used without explanation. 5. Poor naming - variable names such as "locales" and "slash" are vague and do not clearly explain their purpose or contents. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Feature envy2 Long method3 Duplicate code - the same code is repeated multiple times within the method 4 Magic numbers - the values | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 2 | 1739 | 11836 | major | ||
| 1397 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 10854 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 1397 | 10854 | minor | |
| 1026 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy (multiple occurrences of using the same object's methods/properties) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method2 Duplicate code3 Feature envy (multiple occurrences of using the same object's methods/properties) | t | f | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1026 | 9361 | minor | ||
| 1387 | { "output": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | 1. data class | t | t | t | 0 | 10837 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 1387 | 10837 | major | ||
| 1029 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 9382 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1029 | 9382 | major | |
| 3381 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6543 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 3381 | 6543 | major | ||
| 2361 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | Long method | t | f | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 2 | 2361 | 14251 | major | ||
| 208 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FastRTrace { static final class Helper extends RBaseNode { @Child private GetFunctions.Get getNode; @Child private EnvFunctions.TopEnv topEnv; @Child private FrameFunctions.ParentFrame parentFrame; protected Object getWhere(VirtualFrame frame) { if (topEnv == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); topEnv = insert(TopEnvNodeGen.create()); } if (parentFrame == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); parentFrame = insert(ParentFrameNodeGen.create()); } return topEnv.execute(frame, parentFrame.execute(frame, 1), RNull.instance); } protected Object getFunction(VirtualFrame frame, Object what, Object where) { if (getNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); getNode = insert(GetNodeGen.create()); } return getNode.execute(frame, what, where, RType.Function.getName(), true); } protected void checkWhat(Object what) { if (what == RMissing.instance) { throw error(RError.Message.ARGUMENT_MISSING, "what"); } } protected RFunction checkFunction(Object what) { if (what instanceof RFunction) { RFunction func = (RFunction) what; if (func.isBuiltin()) { throw error(RError.Message.GENERIC, "builtin functions cannot be traced"); } else { return func; } } else { throw error(RError.Message.ARG_MUST_BE_CLOSURE); } } } @RBuiltin(name = ".fastr.trace", visibility = CUSTOM, kind = PRIMITIVE, parameterNames = {"what", "tracer", "exit", "at", "print", "signature", "where"}, behavior = COMPLEX) public abstract static class Trace extends RBuiltinNode.Arg7 { @Child private TraceFunctions.PrimTrace primTrace; @Child private CastLogicalNode castLogical; @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @Child private Helper helper = new Helper(); static { Casts.noCasts(Trace.class); } @Specialization protected Object trace(VirtualFrame frame, Object whatObj, Object tracer, Object exit, Object at, Object printObj, Object signature, Object whereObj) { Object what = whatObj; helper.checkWhat(what); Object where = whereObj; if (where == RMissing.instance) { where = helper.getWhere(frame); } String funcName = RRuntime.asString(what); if (funcName != null) { what = helper.getFunction(frame, what, where); } RFunction func = helper.checkFunction(what); if (tracer == RMissing.instance && exit == RMissing.instance && at == RMissing.instance && printObj == RMissing.instance && signature == RMissing.instance) { // simple case, nargs() == 1, corresponds to .primTrace that has invisible output if (primTrace == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); primTrace = insert(PrimTraceNodeGen.create()); } Object result = primTrace.execute(frame, func); visibility.execute(frame, false); return result; } if (at != RMissing.instance) { throw RError.nyi(this, "'at'"); } boolean print = true; if (printObj != RMissing.instance) { if (castLogical == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castLogical = insert(CastLogicalNodeGen.create(false, false, false)); } print = RRuntime.fromLogical((byte) castLogical.doCast(printObj)); } complexCase(func, tracer, exit, at, print, signature); visibility.execute(frame, true); return Utils.toString(func); } @TruffleBoundary private void complexCase(RFunction func, Object tracerObj, @SuppressWarnings("unused") Object exit, Object at, boolean print, @SuppressWarnings("unused") Object signature) { // the complex case RPairList tracer; if (tracerObj instanceof RFunction) { Closure closure = Closure.createLanguageClosure(RASTUtils.createCall(tracerObj, false, ArgumentsSignature.empty(0)).asRNode()); tracer = RDataFactory.createLanguage(closure); } else if ((tracerObj instanceof RPairList && ((RPairList) tracerObj).isLanguage())) { tracer = (RPairList) tracerObj; } else { throw error(RError.Message.GENERIC, "tracer is unexpected type"); } TraceHandling.enableStatementTrace(func, tracer, at, print); } } @RBuiltin(name = ".fastr.untrace", visibility = OFF, kind = PRIMITIVE, parameterNames = {"what", "signature", "where"}, behavior = COMPLEX) public abstract static class Untrace extends RBuiltinNode.Arg3 { @Child private TraceFunctions.PrimUnTrace primUnTrace; @Child private Helper helper = new Helper(); static { Casts.noCasts(Untrace.class); } @Specialization protected Object untrace(VirtualFrame frame, Object whatObj, Object signature, Object whereObj) { Object what = whatObj; helper.checkWhat(what); Object where = whereObj; if (where == RMissing.instance) { where = helper.getWhere(frame); } String funcName = RRuntime.asString(what); if (funcName != null) { what = helper.getFunction(frame, what, where); } RFunction func = helper.checkFunction(what); if (signature == RMissing.instance) { if (primUnTrace == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); primUnTrace = insert(PrimUnTraceNodeGen.create()); } primUnTrace.execute(frame, func); } else { throw RError.nyi(this, "method tracing"); } return Utils.toString(func); } } } |
blob | long method, blob | t | t | t | long method | 0 | 2310 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/fastr/FastRTrace.java/#L70-L223 | 1 | 208 | 2310 | critical | |
| 1034 | { "response": "YES I found bad smells", "bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | blob, long method | t | t | t | blob | 0 | 9396 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/backtracking/ide/contentassist/antlr/internal/InternalExBeeLangTestLanguageParser.java/#L7286-L7317 | 1 | 1034 | 9396 | minor | |
| 88 | {"message": "YES I found bad smells", "bad_smells_found": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | blob, data class | t | t | t | blob | 0 | 1229 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 1 | 88 | 1229 | critical | |
| 329 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SageRuntimeException extends RuntimeException implements SageExceptable { protected final int kind; public SageRuntimeException() { kind = UNKNOWN; } public SageRuntimeException(String message, int kind) { super(message); this.kind = kind; } public SageRuntimeException(Throwable cause, int kind) { super(cause); this.kind = kind; } public SageRuntimeException(String message, Throwable cause, int kind) { super(message, cause); this.kind = kind; } public int getKind() { return (kind); } public boolean isKind(int kind) { return ((this.kind & kind) != 0); } public String getMessage() { return ("kind=" + kind + "; " + super.getMessage()); } } |
data class | data class | t | t | t | 0 | 3387 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/tv/sage/SageRuntimeException.java/#L23-L68 | 1 | 329 | 3387 | major | ||
| 311 | YES, I found bad smellsThe bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getTraceback() { return traceback; } |
feature envy | Feature envy | t | f | t | 0 | 3207 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-jupyter/src/main/java/org/apache/zeppelin/jupyter/nbformat/Error.java/#L48-L50 | 2 | 311 | 3207 | critical | ||
| 1059 | { "output": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Param { @Nullable private String name; @Nullable private String value; /** * Set the raw name of the parameter. */ public void setName(@Nullable String name) { this.name = name; } /** * Return the raw parameter name. */ @Nullable public String getName() { return this.name; } /** * Set the raw value of the parameter. */ public void setValue(@Nullable String value) { this.value = value; } /** * Return the raw parameter value. */ @Nullable public String getValue() { return this.value; } @Override public String toString() { return "JSP Tag Param: name '" + this.name + "', value '" + this.value + "'"; } } |
data class | data class | t | t | t | 0 | 9530 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/Param.java/#L32-L77 | 1 | 1059 | 9530 | minor | ||
| 780 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7455 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 780 | 7455 | minor | ||
| 99 | {"message":"YES I found bad smells","bad smells are":["1.Long method","2.Complex method","3.Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | 1.long method, 2.complex method, 3.feature envy | t | t | t | 2.complex method, 3.feature envy | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 99 | 1298 | minor | |
| 173 | { "response": "YES I found bad smells", "the bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 173 | 2041 | minor | |
| 5481 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 2 | 5481 | 1263 | major | |
| 2571 | YES I found bad smells The bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 2571 | 14900 | minor | ||
| 2076 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | data class | t | t | t | 0 | 13050 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 1 | 2076 | 13050 | major | ||
| 490 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 4881 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 490 | 4881 | major | ||
| 967 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | data class | t | t | t | 0 | 8646 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 967 | 8646 | major | ||
| 1925 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 12434 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 1925 | 12434 | critical | ||
| 1515 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1515 | 11164 | minor | |
| 1106 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 1 | 1106 | 9879 | major | |
| 1325 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10702 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1325 | 10702 | minor | |
| 1269 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10565 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1269 | 10565 | minor | ||
| 5444 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 15311 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 5444 | 15311 | critical | ||
| 240 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2628 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 2 | 240 | 2628 | major | |
| 2287 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | blob, data class | t | t | t | blob | 0 | 13890 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 1 | 2287 | 13890 | major | |
| 2180 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 2180 | 13413 | minor | ||
| 2360 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | data class, long method | t | t | t | long method | 0 | 14236 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 1 | 2360 | 14236 | critical | |
| 4048 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 4048 | 10697 | critical | ||
| 890 | {"response": "YES I found bad smells", "bad smells are": ["3. Long Method", "4. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | 3. long method, 4. data class | t | t | t | 3. long method | 0 | 8082 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 890 | 8082 | minor | |
| 1754 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | 1. data class | t | t | t | 0 | 11867 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 1754 | 11867 | minor | ||
| 2268 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy 3. Magic Numbers (such as the hardcoded value "80" in the method) 4. Inconsistent coding style (such as the mix of tabs and spaces) 5. Code duplication (such as the duplicate calls to LOG.isTraceEnabled()) 6. Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null) 7. Use of deprecated methods (such as FileSystem.get(new URI(), Configuration)) 8. Poor exception handling (such as catching a generic IOException instead of specific exceptions) 9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) 10. Inefficient data structures (such as using nested Map and List structures instead of custom classes) 11. Insufficient comments and documentation (such as not providing javadocs for public methods and classes) 12. Use of raw types (such as Map, List without specifying the types) 13. Poor readability (such as the lack of indentation and the complex nested loops and conditional statements) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Feature Envy3 Magic Numbers (such as the hardcoded value "80" in the method)4 Inconsistent coding style (such as the mix of tabs and spaces)5 Code duplication (such as the duplicate calls to LOGisTraceEnabled())6 Insufficient argument validation (such as not checking if the list passed to handleBulkLoad() is null)7 Use of deprecated methods (such as FileSystemget(new URI(), Configuration))8 Poor exception handling (such as catching a generic IOException instead of specific exceptions)9 Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | t | f | t | Configuration))8. Poor exception handling (such as catching a generic IOException instead of specific exceptions)9. Poor naming convention (such as the variable names "use" and "useFS" which are similar and could be confusing) | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2268 | 13747 | critical | |
| 1449 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class NewNodePresentation { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; private NewNodePresentation(Builder builder) { this.nodeText = builder.nodeText; this.nodeTextStyle = builder.nodeTextStyle; this.nodeInfoText = builder.nodeInfoText; this.nodeInfoTextStyle = builder.nodeInfoTextStyle; this.icon = builder.icon; this.userElement = builder.userElement; } public String getNodeText() { return nodeText; } public StyleConfigurator getNodeTextStyle() { return nodeTextStyle; } public String getNodeInfoText() { return nodeInfoText; } public StyleConfigurator getNodeInfoTextStyle() { return nodeInfoTextStyle; } public SVGResource getIcon() { return icon; } public Element getUserElement() { return userElement; } public static class Builder { private String nodeText; private StyleConfigurator nodeTextStyle; private String nodeInfoText; private StyleConfigurator nodeInfoTextStyle; private SVGResource icon; private Element userElement; public Builder() {} public Builder withNodeText(String nodeText) { this.nodeText = nodeText; return this; } public Builder withNodeTextStyle(StyleConfigurator nodeTextStyle) { this.nodeTextStyle = nodeTextStyle; return this; } public Builder withNodeInfoText(String nodeInfoText) { this.nodeInfoText = nodeInfoText; return this; } public Builder withNodeIntoTextStyle(StyleConfigurator nodeInfoTextStyle) { this.nodeInfoTextStyle = nodeInfoTextStyle; return this; } public Builder withIcon(SVGResource icon) { this.icon = icon; return this; } public Builder withUserElement(Element userElement) { this.userElement = userElement; return this; } public NewNodePresentation build() { return new NewNodePresentation(this); } } } |
data class | data class | t | t | t | 0 | 10991 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/presentation/NewNodePresentation.java/#L25-L111 | 1 | 1449 | 10991 | minor | ||
| 1536 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
data class | Data Class | t | f | t | 0 | 11219 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 1536 | 11219 | minor | ||
| 1282 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10603 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1282 | 10603 | minor | |
| 1913 | YES, I found bad smells The bad smells are: long method, switch statements, feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method, switch statements, feature envy | t | f | t | switch statements, feature envy | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 1913 | 12402 | minor | |
| 1679 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 1679 | 11653 | minor | |
| 2405 | { "message": "YES I found bad smells", "bad_smells": [ { "name": "Long Method" }, { "name": "Feature Envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
feature envy | name: long method, name: feature envy | t | t | t | name: long method | 0 | 14386 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 2405 | 14386 | minor | |
| 2257 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseQuotedValue(byte prev) throws IOException { final byte newLine = this.newLine; final byte delimiter = this.delimiter; final TextOutput output = this.output; final TextInput input = this.input; final byte quote = this.quote; ch = input.nextCharNoNewLineCheck(); while (!(prev == quote && (ch == delimiter || ch == newLine || isWhite(ch)))) { if (ch != quote) { if (prev == quote) { // unescaped quote detected if (parseUnescapedQuotes) { output.append(quote); output.append(ch); parseQuotedValue(ch); break; } else { throw new TextParsingException( context, "Unescaped quote character '" + quote + "' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input."); } } output.append(ch); prev = ch; } else if (prev == quoteEscape) { output.append(quote); prev = NULL_BYTE; } else { prev = ch; } ch = input.nextCharNoNewLineCheck(); } // Handles whitespaces after quoted value: // Whitespaces are ignored (i.e., ch <= ' ') if they are not used as delimiters (i.e., ch != ' ') // For example, in tab-separated files (TSV files), '\t' is used as delimiter and should not be ignored // Content after whitespaces may be parsed if 'parseUnescapedQuotes' is enabled. if (ch != newLine && ch <= ' ' && ch != delimiter) { final DrillBuf workBuf = this.workBuf; workBuf.resetWriterIndex(); do { // saves whitespaces after value workBuf.writeByte(ch); ch = input.nextChar(); // found a new line, go to next record. if (ch == newLine) { return; } } while (ch <= ' ' && ch != delimiter); // there's more stuff after the quoted value, not only empty spaces. if (!(ch == delimiter || ch == newLine) && parseUnescapedQuotes) { output.append(quote); for(int i =0; i < workBuf.writerIndex(); i++){ output.append(workBuf.getByte(i)); } // the next character is not the escape character, put it there if (ch != quoteEscape) { output.append(ch); } // sets this character as the previous character (may be escaping) // calls recursively to keep parsing potentially quoted content parseQuotedValue(ch); } } if (!(ch == delimiter || ch == newLine)) { throw new TextParsingException(context, "Unexpected character '" + ch + "' following quoted value of CSV field. Expecting '" + delimiter + "'. Cannot parse CSV input."); } } |
long method | long method | t | t | t | 0 | 13693 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/text/compliant/TextReader.java/#L226-L300 | 1 | 2257 | 13693 | major | ||
| 2582 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 2582 | 14956 | minor | ||
| 72 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CertificatePolicyMap { private CertificatePolicyId issuerDomain; private CertificatePolicyId subjectDomain; /** * Create a CertificatePolicyMap with the passed CertificatePolicyId's. * * @param issuer the CertificatePolicyId for the issuer CA. * @param subject the CertificatePolicyId for the subject CA. */ public CertificatePolicyMap(CertificatePolicyId issuer, CertificatePolicyId subject) { this.issuerDomain = issuer; this.subjectDomain = subject; } /** * Create the CertificatePolicyMap from the DER encoded value. * * @param val the DER encoded value of the same. */ public CertificatePolicyMap(DerValue val) throws IOException { if (val.tag != DerValue.tag_Sequence) { throw new IOException("Invalid encoding for CertificatePolicyMap"); } issuerDomain = new CertificatePolicyId(val.data.getDerValue()); subjectDomain = new CertificatePolicyId(val.data.getDerValue()); } /** * Return the issuer CA part of the policy map. */ public CertificatePolicyId getIssuerIdentifier() { return (issuerDomain); } /** * Return the subject CA part of the policy map. */ public CertificatePolicyId getSubjectIdentifier() { return (subjectDomain); } /** * Returns a printable representation of the CertificatePolicyId. */ public String toString() { String s = "CertificatePolicyMap: [\n" + "IssuerDomain:" + issuerDomain.toString() + "SubjectDomain:" + subjectDomain.toString() + "]\n"; return (s); } /** * Write the CertificatePolicyMap to the DerOutputStream. * * @param out the DerOutputStream to write the object to. * @exception IOException on errors. */ public void encode(DerOutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); issuerDomain.encode(tmp); subjectDomain.encode(tmp); out.write(DerValue.tag_Sequence,tmp); } } |
data class | data class | t | t | t | 0 | 1106 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/CertificatePolicyMap.java/#L38-L106 | 1 | 72 | 1106 | minor | ||
| 1506 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 11150 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1506 | 11150 | critical | ||
| 952 | YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ConfigurationInfo(CompositeData cd) { this.settings = createMap(cd.get("settings")); this.name = (String) cd.get("name"); this.label = (String) cd.get("label"); this.description = (String) cd.get("description"); this.provider = (String) cd.get("provider"); this.contents = (String) cd.get("contents"); } |
feature envy | Long method2Feature envy | t | f | t | 0 | 8527 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.management.jfr/share/classes/jdk/management/jfr/ConfigurationInfo.java/#L63-L70 | 2 | 952 | 8527 | major | ||
| 448 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 448 | 4366 | minor | ||
| 5494 | {"output": "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void writeEdge(I srcId, V srcValue, Edge edge) throws IOException, InterruptedException { if (txcounter == txsize) { txcounter = 0; isFirstElement = true; stopConnection(); startConnection(); } try { JSONObject jsonEdge; String suffix; /* extract the JSON object of the vertex */ jsonEdge = getEdge(srcId, srcValue, edge); /* determine the suffix to add the object into the JSON array */ if (isFirstElement) { isFirstElement = false; suffix = ""; } else { suffix = ","; } rexsterBufferedStream.write(suffix + jsonEdge); txcounter += 1; } catch (JSONException e) { throw new InterruptedException("Error writing the edge: " + e.getMessage()); } } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 2683 | https://github.com/apache/giraph/blob/d3bf4a2cf5347f7cfd9d217b216c906cb7801217/giraph-rexster/giraph-rexster-io/src/main/java/org/apache/giraph/rexster/io/RexsterEdgeOutputFormat.java/#L167-L198 | 2 | 5494 | 2683 | minor |
| 2463 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | long method | t | t | t | 0 | 14551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 1 | 2463 | 14551 | major | ||
| 197 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 1 | 197 | 2237 | minor | ||
| 5166 | {"message": "YES I found bad smells\nthe bad smells are: 4. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 4. long method | t | t | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5166 | 14457 | major | ||
| 2514 | { "output": "YES I found bad smells", "bad smells are:": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GridH2DmlResponse implements Message, GridCacheQueryMarshallable { /** */ private static final long serialVersionUID = 0L; /** Request id. */ @GridToStringInclude private long reqId; /** Number of updated rows. */ @GridToStringInclude private long updCnt; /** Error message. */ @GridToStringInclude private String err; /** Keys that failed. */ @GridToStringInclude @GridDirectTransient private Object[] errKeys; /** Keys that failed (after marshalling). */ private byte[] errKeysBytes; /** * Default constructor. */ public GridH2DmlResponse() { // No-op. } /** * Constructor. * * @param reqId Request id. * @param updCnt Updated row number. * @param errKeys Erroneous keys. * @param error Error message. */ public GridH2DmlResponse(long reqId, long updCnt, Object[] errKeys, String error) { this.reqId = reqId; this.updCnt = updCnt; this.errKeys = errKeys; this.err = error; } /** * @return Request id. */ public long requestId() { return reqId; } /** * @return Update counter. */ public long updateCounter() { return updCnt; } /** * @return Error keys. */ public Object[] errorKeys() { return errKeys; } /** * @return Error message. */ public String error() { return err; } /** {@inheritDoc} */ @Override public void marshall(Marshaller m) { if (errKeysBytes != null || errKeys == null) return; try { errKeysBytes = U.marshal(m, errKeys); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @SuppressWarnings("IfMayBeConditional") @Override public void unmarshall(Marshaller m, GridKernalContext ctx) { if (errKeys != null || errKeysBytes == null) return; try { final ClassLoader ldr = U.resolveClassLoader(ctx.config()); if (m instanceof BinaryMarshaller) // To avoid deserializing of enum types. errKeys = ((BinaryMarshaller)m).binaryMarshaller().unmarshal(errKeysBytes, ldr); else errKeys = U.unmarshal(m, errKeysBytes, ldr); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridH2DmlResponse.class, this); } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { writer.setBuffer(buf); if (!writer.isHeaderWritten()) { if (!writer.writeHeader(directType(), fieldsCount())) return false; writer.onHeaderWritten(); } switch (writer.state()) { case 0: if (!writer.writeString("err", err)) return false; writer.incrementState(); case 1: if (!writer.writeByteArray("errKeysBytes", errKeysBytes)) return false; writer.incrementState(); case 2: if (!writer.writeLong("reqId", reqId)) return false; writer.incrementState(); case 3: if (!writer.writeLong("updCnt", updCnt)) return false; writer.incrementState(); } return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; switch (reader.state()) { case 0: err = reader.readString("err"); if (!reader.isLastRead()) return false; reader.incrementState(); case 1: errKeysBytes = reader.readByteArray("errKeysBytes"); if (!reader.isLastRead()) return false; reader.incrementState(); case 2: reqId = reader.readLong("reqId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 3: updCnt = reader.readLong("updCnt"); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(GridH2DmlResponse.class); } /** {@inheritDoc} */ @Override public short directType() { return -56; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 4; } @Override public void onAckReceived() { // No-op } } |
data class | data class | t | t | t | 0 | 14693 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/msg/GridH2DmlResponse.java/#L38-L249 | 1 | 2514 | 14693 | minor | ||
| 1969 | YES I found bad smells the bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method 2 Feature Envy | t | f | t | 0 | 12606 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1969 | 12606 | major | ||
| 313 | {"response": "YES I found bad smells", "detected_bad_smells": ["Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void transformKeyReferences(RefTransformer visitor) { configs.forEach(c -> c.transformKeyReferences(visitor)); } |
feature envy | feature envy | t | t | t | 0 | 3219 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/resources/ResTableTypeSpec.java/#L166-L168 | 1 | 313 | 3219 | critical | ||
| 1559 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 11300 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1559 | 11300 | minor | |
| 1992 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | data class | t | t | t | 0 | 12687 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 1 | 1992 | 12687 | major | ||
| 3920 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ServletContextAttributeFactoryBean implements FactoryBean, ServletContextAware { @Nullable private String attributeName; @Nullable private Object attribute; /** * Set the name of the ServletContext attribute to expose. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } @Override public void setServletContext(ServletContext servletContext) { if (this.attributeName == null) { throw new IllegalArgumentException("Property 'attributeName' is required"); } this.attribute = servletContext.getAttribute(this.attributeName); if (this.attribute == null) { throw new IllegalStateException("No ServletContext attribute '" + this.attributeName + "' found"); } } @Override @Nullable public Object getObject() throws Exception { return this.attribute; } @Override public Class getObjectType() { return (this.attribute != null ? this.attribute.getClass() : null); } @Override public boolean isSingleton() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 10262 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/ServletContextAttributeFactoryBean.java/#L45-L89 | 1 | 3920 | 10262 | major | |
| 1481 | { "message": "YES I found bad smells", "bad smells are": [ "1. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ComponentRenderInfo extends BaseRenderInfo { public static final String LAYOUT_DIFFING_ENABLED = "layout_diffing_enabled"; public static final String PERSISTENCE_ENABLED = "is_persistence_enabled"; private final Component mComponent; @Nullable private final EventHandler mRenderCompleteEventHandler; public static Builder create() { return new Builder(); } private ComponentRenderInfo(Builder builder) { super(builder); if (builder.mComponent == null) { throw new IllegalStateException("Component must be provided."); } mComponent = builder.mComponent; mRenderCompleteEventHandler = builder.mRenderCompleteEventEventHandler; } /** Create empty {@link ComponentRenderInfo}. */ public static RenderInfo createEmpty() { return create().component(new EmptyComponent()).build(); } @Override public Component getComponent() { return mComponent; } @Override @Nullable public EventHandler getRenderCompleteEventHandler() { return mRenderCompleteEventHandler; } @Override public boolean rendersComponent() { return true; } @Override public String getName() { return mComponent.getSimpleName(); } public static class Builder extends BaseRenderInfo.Builder { private Component mComponent; private EventHandler mRenderCompleteEventEventHandler; /** Specify {@link Component} that will be rendered as an item of the list. */ public Builder component(Component component) { this.mComponent = component; return this; } public Builder renderCompleteHandler( EventHandler renderCompleteEventHandler) { this.mRenderCompleteEventEventHandler = renderCompleteEventHandler; return this; } public Builder component(Component.Builder builder) { return component(builder.build()); } public ComponentRenderInfo build() { return new ComponentRenderInfo(this); } } private static class EmptyComponent extends Component { protected EmptyComponent() { super("EmptyComponent"); } @Override protected Component onCreateLayout(ComponentContext c) { return Column.create(c).build(); } @Override public boolean isEquivalentTo(Component other) { return EmptyComponent.this == other || (other != null && EmptyComponent.this.getClass() == other.getClass()); } } } |
blob | 1. blob | t | t | t | 0 | 11082 | https://github.com/facebook/litho/blob/19503b819b97e17d02f584633508dca8c646911a/litho-widget/src/main/java/com/facebook/litho/widget/ComponentRenderInfo.java/#L27-L118 | 1 | 1481 | 11082 | minor | ||
| 1878 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 1878 | 12273 | minor | ||
| 4024 | YES, I found bad smells 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void endAccess() { super.endAccess() ; if(manager instanceof ClusterManagerBase) { ((ClusterManagerBase)manager).registerSessionAtReplicationValve(this); } } |
feature envy | Feature envy | t | f | t | 0 | 10635 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/catalina/ha/session/DeltaSession.java/#L412-L418 | 2 | 4024 | 10635 | critical | ||
| 2448 | YES, I found bad smells, the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14498 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 2448 | 14498 | minor | |
| 1154 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 1154 | 10137 | critical | |
| 1495 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 1495 | 11124 | major | |
| 1338 | { "answer": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | long method | t | t | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 1 | 1338 | 10733 | major | ||
| 1640 | {"message":"YES I found bad smells","the bad smells are":["Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SeekableXZInputStream extends SeekableInputStream { /** * Cache for big arrays. */ private final ArrayCache arrayCache; /** * The input stream containing XZ compressed data. */ private SeekableInputStream in; /** * Memory usage limit after the memory usage of the IndexDecoders have * been substracted. */ private final int memoryLimit; /** * Memory usage of the IndexDecoders. * memoryLimit + indexMemoryUsage equals the original * memory usage limit that was passed to the constructor. */ private int indexMemoryUsage = 0; /** * List of IndexDecoders, one for each Stream in the file. * The list is in reverse order: The first element is * the last Stream in the file. */ private final ArrayList streams = new ArrayList(); /** * Bitmask of all Check IDs seen. */ private int checkTypes = 0; /** * Uncompressed size of the file (all Streams). */ private long uncompressedSize = 0; /** * Uncompressed size of the largest XZ Block in the file. */ private long largestBlockSize = 0; /** * Number of XZ Blocks in the file. */ private int blockCount = 0; /** * Size and position information about the current Block. * If there are no Blocks, all values will be -1. */ private final BlockInfo curBlockInfo; /** * Temporary (and cached) information about the Block whose information * is queried via getBlockPos and related functions. */ private final BlockInfo queriedBlockInfo; /** * Integrity Check in the current XZ Stream. The constructor leaves * this to point to the Check of the first Stream. */ private Check check; /** * Flag indicating if the integrity checks will be verified. */ private final boolean verifyCheck; /** * Decoder of the current XZ Block, if any. */ private BlockInputStream blockDecoder = null; /** * Current uncompressed position. */ private long curPos = 0; /** * Target position for seeking. */ private long seekPos; /** * True when seek(long) has been called but the actual * seeking hasn't been done yet. */ private boolean seekNeeded = false; /** * True when end of the file was reached. This can be cleared by * calling seek(long). */ private boolean endReached = false; /** * Pending exception from an earlier error. */ private IOException exception = null; /** * Temporary buffer for read(). This avoids reallocating memory * on every read() call. */ private final byte[] tempBuf = new byte[1]; /** * Creates a new seekable XZ decompressor without a memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in) throws IOException { this(in, -1); } /** * Creates a new seekable XZ decompressor without a memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream) except that * this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache) throws IOException { this(in, -1, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit) throws IOException { this(in, memoryLimit, true); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, ArrayCache arrayCache) throws IOException { this(in, memoryLimit, true, arrayCache); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * Note that integrity check verification should almost never be disabled. * Possible reasons to disable integrity check verification: * * Trying to recover data from a corrupt .xz file. * Speeding up decompression. This matters mostly with SHA-256 * or with files that have compressed extremely well. It's recommended * that integrity checking isn't disabled for performance reasons * unless the file integrity is verified externally in some other * way. * * * verifyCheck only affects the integrity check of * the actual compressed data. The CRC32 fields in the headers * are always verified. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.6 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck) throws IOException { this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); } /** * Creates a new seekable XZ decomporessor with an optional * memory usage limit and ability to disable verification * of integrity checks. * * This is identical to * SeekableXZInputStream(SeekableInputStream,int,boolean) * except that this also takes the arrayCache argument. * * @param in seekable input stream containing one or more * XZ Streams; the whole input stream is used * * @param memoryLimit memory usage limit in kibibytes (KiB) * or -1 to impose no * memory usage limit * * @param verifyCheck if true, the integrity checks * will be verified; this should almost never * be set to false * * @param arrayCache cache to be used for allocating large arrays * * @throws XZFormatException * input is not in the XZ format * * @throws CorruptedInputException * XZ data is corrupt or truncated * * @throws UnsupportedOptionsException * XZ headers seem valid but they specify * options not supported by this implementation * * @throws MemoryLimitException * decoded XZ Indexes would need more memory * than allowed by the memory usage limit * * @throws EOFException * less than 6 bytes of input was available * from in, or (unlikely) the size * of the underlying stream got smaller while * this was reading from it * * @throws IOException may be thrown by in * * @since 1.7 */ public SeekableXZInputStream(SeekableInputStream in, int memoryLimit, boolean verifyCheck, ArrayCache arrayCache) throws IOException { this.arrayCache = arrayCache; this.verifyCheck = verifyCheck; this.in = in; DataInputStream inData = new DataInputStream(in); // Check the magic bytes in the beginning of the file. { in.seek(0); byte[] buf = new byte[XZ.HEADER_MAGIC.length]; inData.readFully(buf); if (!Arrays.equals(buf, XZ.HEADER_MAGIC)) throw new XZFormatException(); } // Get the file size and verify that it is a multiple of 4 bytes. long pos = in.length(); if ((pos & 3) != 0) throw new CorruptedInputException( "XZ file size is not a multiple of 4 bytes"); // Parse the headers starting from the end of the file. byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; long streamPadding = 0; while (pos > 0) { if (pos < DecoderUtil.STREAM_HEADER_SIZE) throw new CorruptedInputException(); // Read the potential Stream Footer. in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE); inData.readFully(buf); // Skip Stream Padding four bytes at a time. // Skipping more at once would be faster, // but usually there isn't much Stream Padding. if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00 && buf[11] == 0x00) { streamPadding += 4; pos -= 4; continue; } // It's not Stream Padding. Update pos. pos -= DecoderUtil.STREAM_HEADER_SIZE; // Decode the Stream Footer and check if Backward Size // looks reasonable. StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf); if (streamFooter.backwardSize >= pos) throw new CorruptedInputException( "Backward Size in XZ Stream Footer is too big"); // Check that the Check ID is supported. Store it in case this // is the first Stream in the file. check = Check.getInstance(streamFooter.checkType); // Remember which Check IDs have been seen. checkTypes |= 1 << streamFooter.checkType; // Seek to the beginning of the Index. in.seek(pos - streamFooter.backwardSize); // Decode the Index field. IndexDecoder index; try { index = new IndexDecoder(in, streamFooter, streamPadding, memoryLimit); } catch (MemoryLimitException e) { // IndexDecoder doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } // Update the memory usage and limit counters. indexMemoryUsage += index.getMemoryUsage(); if (memoryLimit >= 0) { memoryLimit -= index.getMemoryUsage(); assert memoryLimit >= 0; } // Remember the uncompressed size of the largest Block. if (largestBlockSize < index.getLargestBlockSize()) largestBlockSize = index.getLargestBlockSize(); // Calculate the offset to the beginning of this XZ Stream and // check that it looks sane. long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE; if (pos < off) throw new CorruptedInputException("XZ Index indicates " + "too big compressed size for the XZ Stream"); // Seek to the beginning of this Stream. pos -= off; in.seek(pos); // Decode the Stream Header. inData.readFully(buf); StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf); // Verify that the Stream Header matches the Stream Footer. if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter)) throw new CorruptedInputException( "XZ Stream Footer does not match Stream Header"); // Update the total uncompressed size of the file and check that // it doesn't overflow. uncompressedSize += index.getUncompressedSize(); if (uncompressedSize < 0) throw new UnsupportedOptionsException("XZ file is too big"); // Update the Block count and check that it fits into an int. blockCount += index.getRecordCount(); if (blockCount < 0) throw new UnsupportedOptionsException( "XZ file has over " + Integer.MAX_VALUE + " Blocks"); // Add this Stream to the list of Streams. streams.add(index); // Reset to be ready to parse the next Stream. streamPadding = 0; } assert pos == 0; // Save it now that indexMemoryUsage has been substracted from it. this.memoryLimit = memoryLimit; // Store the relative offsets of the Streams. This way we don't // need to recalculate them in this class when seeking; the // IndexDecoder instances will handle them. IndexDecoder prev = streams.get(streams.size() - 1); for (int i = streams.size() - 2; i >= 0; --i) { IndexDecoder cur = streams.get(i); cur.setOffsets(prev); prev = cur; } // Initialize curBlockInfo to point to the first Stream. // The blockNumber will be left to -1 so that .hasNext() // and .setNext() work to get the first Block when starting // to decompress from the beginning of the file. IndexDecoder first = streams.get(streams.size() - 1); curBlockInfo = new BlockInfo(first); // queriedBlockInfo needs to be allocated too. The Stream used for // initialization doesn't matter though. queriedBlockInfo = new BlockInfo(first); } /** * Gets the types of integrity checks used in the .xz file. * Multiple checks are possible only if there are multiple * concatenated XZ Streams. * * The returned value has a bit set for every check type that is present. * For example, if CRC64 and SHA-256 were used, the return value is * (1 << XZ.CHECK_CRC64) * | (1 << XZ.CHECK_SHA256). */ public int getCheckTypes() { return checkTypes; } /** * Gets the amount of memory in kibibytes (KiB) used by * the data structures needed to locate the XZ Blocks. * This is usually useless information but since it is calculated * for memory usage limit anyway, it is nice to make it available to too. */ public int getIndexMemoryUsage() { return indexMemoryUsage; } /** * Gets the uncompressed size of the largest XZ Block in bytes. * This can be useful if you want to check that the file doesn't * have huge XZ Blocks which could make seeking to arbitrary offsets * very slow. Note that huge Blocks don't automatically mean that * seeking would be slow, for example, seeking to the beginning of * any Block is always fast. */ public long getLargestBlockSize() { return largestBlockSize; } /** * Gets the number of Streams in the .xz file. * * @since 1.3 */ public int getStreamCount() { return streams.size(); } /** * Gets the number of Blocks in the .xz file. * * @since 1.3 */ public int getBlockCount() { return blockCount; } /** * Gets the uncompressed start position of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedOffset; } /** * Gets the uncompressed size of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.uncompressedSize; } /** * Gets the position where the given compressed Block starts in * the underlying .xz file. * This information is rarely useful to the users of this class. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompPos(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.compressedOffset; } /** * Gets the compressed size of the given Block. * This together with the uncompressed size can be used to calculate * the compression ratio of the specific Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @since 1.3 */ public long getBlockCompSize(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return (queriedBlockInfo.unpaddedSize + 3) & ~3; } /** * Gets integrity check type (Check ID) of the given Block. * * @throws IndexOutOfBoundsException if * blockNumber < 0 or * blockNumber >= getBlockCount(). * * @see #getCheckTypes() * * @since 1.3 */ public int getBlockCheckType(int blockNumber) { locateBlockByNumber(queriedBlockInfo, blockNumber); return queriedBlockInfo.getCheckType(); } /** * Gets the number of the Block that contains the byte at the given * uncompressed position. * * @throws IndexOutOfBoundsException if * pos < 0 or * pos >= length(). * * @since 1.3 */ public int getBlockNumber(long pos) { locateBlockByPos(queriedBlockInfo, pos); return queriedBlockInfo.blockNumber; } /** * Decompresses the next byte from this input stream. * * @return the next decompressed byte, or -1 * to indicate the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read() throws IOException { return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); } /** * Decompresses into an array of bytes. * * If len is zero, no bytes are read and 0 * is returned. Otherwise this will try to decompress len * bytes of uncompressed data. Less than len bytes may * be read only in the following situations: * * The end of the compressed data was reached successfully. * An error is detected after at least one but less than * len bytes have already been successfully * decompressed. The next call with non-zero len * will immediately throw the pending exception. * An exception is thrown. * * * @param buf target buffer for uncompressed data * @param off start offset in buf * @param len maximum number of uncompressed bytes to read * * @return number of bytes read, or -1 to indicate * the end of the compressed stream * * @throws CorruptedInputException * @throws UnsupportedOptionsException * @throws MemoryLimitException * * @throws XZIOException if the stream has been closed * * @throws IOException may be thrown by in */ public int read(byte[] buf, int off, int len) throws IOException { if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) throw new IndexOutOfBoundsException(); if (len == 0) return 0; if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; int size = 0; try { if (seekNeeded) seek(); if (endReached) return -1; while (len > 0) { if (blockDecoder == null) { seek(); if (endReached) break; } int ret = blockDecoder.read(buf, off, len); if (ret > 0) { curPos += ret; size += ret; off += ret; len -= ret; } else if (ret == -1) { blockDecoder = null; } } } catch (IOException e) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if (e instanceof EOFException) e = new CorruptedInputException(); exception = e; if (size == 0) throw e; } return size; } /** * Returns the number of uncompressed bytes that can be read * without blocking. The value is returned with an assumption * that the compressed input data will be valid. If the compressed * data is corrupt, CorruptedInputException may get * thrown before the number of bytes claimed to be available have * been read from this input stream. * * @return the number of uncompressed bytes that can be read * without blocking */ public int available() throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (exception != null) throw exception; if (endReached || seekNeeded || blockDecoder == null) return 0; return blockDecoder.available(); } /** * Closes the stream and calls in.close(). * If the stream was already closed, this does nothing. * * This is equivalent to close(true). * * @throws IOException if thrown by in.close() */ public void close() throws IOException { close(true); } /** * Closes the stream and optionally calls in.close(). * If the stream was already closed, this does nothing. * If close(false) has been called, a further * call of close(true) does nothing (it doesn't call * in.close()). * * If you don't want to close the underlying InputStream, * there is usually no need to worry about closing this stream either; * it's fine to do nothing and let the garbage collector handle it. * However, if you are using {@link ArrayCache}, close(false) * can be useful to put the allocated arrays back to the cache without * closing the underlying InputStream. * * Note that if you successfully reach the end of the stream * (read returns -1), the arrays are * automatically put back to the cache by that read call. In * this situation close(false) is redundant (but harmless). * * @throws IOException if thrown by in.close() * * @since 1.7 */ public void close(boolean closeInput) throws IOException { if (in != null) { if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } try { if (closeInput) in.close(); } finally { in = null; } } } /** * Gets the uncompressed size of this input stream. If there are multiple * XZ Streams, the total uncompressed size of all XZ Streams is returned. */ public long length() { return uncompressedSize; } /** * Gets the current uncompressed position in this input stream. * * @throws XZIOException if the stream has been closed */ public long position() throws IOException { if (in == null) throw new XZIOException("Stream closed"); return seekNeeded ? seekPos : curPos; } /** * Seeks to the specified absolute uncompressed position in the stream. * This only stores the new position, so this function itself is always * very fast. The actual seek is done when read is called * to read at least one byte. * * Seeking past the end of the stream is possible. In that case * read will return -1 to indicate * the end of the stream. * * @param pos new uncompressed read position * * @throws XZIOException * if pos is negative, or * if stream has been closed */ public void seek(long pos) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (pos < 0) throw new XZIOException("Negative seek position: " + pos); seekPos = pos; seekNeeded = true; } /** * Seeks to the beginning of the given XZ Block. * * @throws XZIOException * if blockNumber < 0 or * blockNumber >= getBlockCount(), * or if stream has been closed * * @since 1.3 */ public void seekToBlock(int blockNumber) throws IOException { if (in == null) throw new XZIOException("Stream closed"); if (blockNumber < 0 || blockNumber >= blockCount) throw new XZIOException("Invalid XZ Block number: " + blockNumber); // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos(blockNumber); seekNeeded = true; } /** * Does the actual seeking. This is also called when read * needs a new Block to decode. */ private void seek() throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if (!seekNeeded) { if (curBlockInfo.hasNext()) { curBlockInfo.setNext(); initBlockDecoder(); return; } seekPos = curPos; } seekNeeded = false; // Check if we are seeking to or past the end of the file. if (seekPos >= uncompressedSize) { curPos = seekPos; if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } endReached = true; return; } endReached = false; // Locate the Block that contains the uncompressed target position. locateBlockByPos(curBlockInfo, seekPos); // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) { // Seek to the beginning of the Block. in.seek(curBlockInfo.compressedOffset); // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check.getInstance(curBlockInfo.getCheckType()); // Create a new Block decoder. initBlockDecoder(); curPos = curBlockInfo.uncompressedOffset; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if (seekPos > curPos) { // NOTE: The "if" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos; if (blockDecoder.skip(skipAmount) != skipAmount) throw new CorruptedInputException(); curPos = seekPos; } } /** * Locates the Block that contains the given uncompressed position. */ private void locateBlockByPos(BlockInfo info, long pos) { if (pos < 0 || pos >= uncompressedSize) throw new IndexOutOfBoundsException( "Invalid uncompressed position: " + pos); // Locate the Stream that contains the target position. IndexDecoder index; for (int i = 0; ; ++i) { index = streams.get(i); if (index.hasUncompressedOffset(pos)) break; } // Locate the Block from the Stream that contains the target position. index.locateBlock(info, pos); assert (info.compressedOffset & 3) == 0; assert info.uncompressedSize > 0; assert pos >= info.uncompressedOffset; assert pos < info.uncompressedOffset + info.uncompressedSize; } /** * Locates the given Block and stores information about it * to info. */ private void locateBlockByNumber(BlockInfo info, int blockNumber) { // Validate. if (blockNumber < 0 || blockNumber >= blockCount) throw new IndexOutOfBoundsException( "Invalid XZ Block number: " + blockNumber); // Skip the search if info already points to the correct Block. if (info.blockNumber == blockNumber) return; // Search the Stream that contains the given Block and then // search the Block from that Stream. for (int i = 0; ; ++i) { IndexDecoder index = streams.get(i); if (index.hasRecord(blockNumber)) { index.setBlockInfo(info, blockNumber); return; } } } /** * Initializes a new BlockInputStream. This is a helper function for * seek(). */ private void initBlockDecoder() throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if (blockDecoder != null) { blockDecoder.close(); blockDecoder = null; } blockDecoder = new BlockInputStream( in, check, verifyCheck, memoryLimit, curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize, arrayCache); } catch (MemoryLimitException e) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0; throw new MemoryLimitException( e.getMemoryNeeded() + indexMemoryUsage, memoryLimit + indexMemoryUsage); } catch (IndexIndicatorException e) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException(); } } } |
data class | data class, long method | t | t | t | long method | 0 | 11534 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.tukani.xz/src/org/tukaani/xz/SeekableXZInputStream.java/#L76-L1152 | 1 | 1640 | 11534 | minor | |
| 1173 | { "message": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | 1. long method | t | t | t | 0 | 10199 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1173 | 10199 | minor | ||
| 1753 | YES I found bad smells The bad smells are: 1.Long method 2.Magic numbers 3.Coupled design 4.Dead code 5.Inconsistent formatting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long method2Magic numbers3Coupled design4Dead code 5Inconsistent formatting | t | f | t | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 2 | 1753 | 11865 | minor | ||
| 1806 | {"message": "YES I found bad smells", "bad_smells": [ "Data Class" ]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RequireCapability { private final String namespace; private final String filter; private final String effective; public RequireCapability ( final String namespace, final String filter, final String effective ) { this.namespace = namespace; this.filter = filter; this.effective = effective; } public String getNamespace () { return this.namespace; } public String getFilter () { return this.filter; } public String getEffective () { return this.effective; } } |
data class | Data Class | t | f | t | 0 | 12041 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformation.java/#L377-L406 | 1 | 1806 | 12041 | minor | ||
| 1411 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | 1. long method | t | t | t | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 1 | 1411 | 10900 | major | ||
| 1214 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Switch statement | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2 Feature envy3 Duplicate code4 Switch statement | t | f | t | 0 | 10314 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1214 | 10314 | minor | ||
| 2175 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implements(NfcAdapter.class) public class ShadowNfcAdapter { @RealObject NfcAdapter nfcAdapter; private static boolean hardwareExists = true; private boolean enabled; private Activity enabledActivity; private PendingIntent intent; private IntentFilter[] filters; private String[][] techLists; private Activity disabledActivity; private NdefMessage ndefPushMessage; private boolean ndefPushMessageSet; private NfcAdapter.CreateNdefMessageCallback ndefPushMessageCallback; private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback; @Implementation protected static NfcAdapter getNfcAdapter(Context context) { if (!hardwareExists) { return null; } return ReflectionHelpers.callConstructor(NfcAdapter.class); } @Implementation protected void enableForegroundDispatch( Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) { this.enabledActivity = activity; this.intent = intent; this.filters = filters; this.techLists = techLists; } @Implementation protected void disableForegroundDispatch(Activity activity) { disabledActivity = activity; } /** * Mocks setting NDEF push message so that it could be verified in the test. Use {@link * #getNdefPushMessage()} to verify that message was set. */ @Implementation protected void setNdefPushMessage( NdefMessage message, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.ndefPushMessage = message; this.ndefPushMessageSet = true; } @Implementation protected void setNdefPushMessageCallback( NfcAdapter.CreateNdefMessageCallback callback, Activity activity, Activity... activities) { this.ndefPushMessageCallback = callback; } /** * Sets callback that should be used on successful Android Beam (TM). * * The last registered callback is recalled and can be fetched using {@link * #getOnNdefPushCompleteCallback}. */ @Implementation protected void setOnNdefPushCompleteCallback( NfcAdapter.OnNdefPushCompleteCallback callback, Activity activity, Activity... activities) { if (activity == null) { throw new NullPointerException("activity cannot be null"); } for (Activity a : activities) { if (a == null) { throw new NullPointerException("activities cannot contain null"); } } this.onNdefPushCompleteCallback = callback; } @Implementation protected boolean isEnabled() { return enabled; } /** * Modifies behavior of {@link #getNfcAdapter(Context)} to return {@code null}, to simulate * absence of NFC hardware. */ public static void setNfcHardwareExists(boolean hardwareExists) { ShadowNfcAdapter.hardwareExists = hardwareExists; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Activity getEnabledActivity() { return enabledActivity; } public PendingIntent getIntent() { return intent; } public IntentFilter[] getFilters() { return filters; } public String[][] getTechLists() { return techLists; } public Activity getDisabledActivity() { return disabledActivity; } /** Returns last registered callback, or {@code null} if none was set. */ public NfcAdapter.CreateNdefMessageCallback getNdefPushMessageCallback() { return ndefPushMessageCallback; } public NfcAdapter.OnNdefPushCompleteCallback getOnNdefPushCompleteCallback() { return onNdefPushCompleteCallback; } /** Returns last set NDEF message, or throws {@code IllegalStateException} if it was never set. */ public NdefMessage getNdefPushMessage() { if (!ndefPushMessageSet) { throw new IllegalStateException(); } return ndefPushMessage; } @Resetter public static synchronized void reset() { hardwareExists = true; } } |
data class | data class, long method | t | t | t | long method | 0 | 13394 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNfcAdapter.java/#L15-L155 | 1 | 2175 | 13394 | major | |
| 1046 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9456 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1046 | 9456 | minor | |
| 1961 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public class SingleThreadAccessCheckingTypeSerializer extends TypeSerializer { private static final long serialVersionUID = 131020282727167064L; private final SingleThreadAccessChecker singleThreadAccessChecker; private final TypeSerializer originalSerializer; public SingleThreadAccessCheckingTypeSerializer(TypeSerializer originalSerializer) { this.singleThreadAccessChecker = new SingleThreadAccessChecker(); this.originalSerializer = originalSerializer; } @Override public boolean isImmutableType() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.isImmutableType(); } } @Override public TypeSerializer duplicate() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializer<>(originalSerializer.duplicate()); } } @Override public T createInstance() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.createInstance(); } } @Override public T copy(T from) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from); } } @Override public T copy(T from, T reuse) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.copy(from, reuse); } } @Override public int getLength() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.getLength(); } } @Override public void serialize(T record, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.serialize(record, target); } } @Override public T deserialize(DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(source); } } @Override public T deserialize(T reuse, DataInputView source) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.deserialize(reuse, source); } } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { originalSerializer.copy(source, target); } } @Override public boolean equals(Object obj) { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return obj == this || (obj != null && obj.getClass() == getClass() && originalSerializer.equals(obj)); } } @Override public int hashCode() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return originalSerializer.hashCode(); } } @Override public TypeSerializerSnapshot snapshotConfiguration() { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { return new SingleThreadAccessCheckingTypeSerializerSnapshot<>(this); } } public static class SingleThreadAccessCheckingTypeSerializerSnapshot extends CompositeTypeSerializerSnapshot> { @SuppressWarnings({"unchecked", "unused"}) public SingleThreadAccessCheckingTypeSerializerSnapshot() { super((Class>) (Class) SingleThreadAccessCheckingTypeSerializer.class); } SingleThreadAccessCheckingTypeSerializerSnapshot(SingleThreadAccessCheckingTypeSerializer serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return 1; } @Override protected TypeSerializer[] getNestedSerializers(SingleThreadAccessCheckingTypeSerializer outerSerializer) { return new TypeSerializer[] { outerSerializer.originalSerializer }; } @SuppressWarnings("unchecked") @Override protected SingleThreadAccessCheckingTypeSerializer createOuterSerializerWithNestedSerializers( TypeSerializer[] nestedSerializers) { return new SingleThreadAccessCheckingTypeSerializer<>((TypeSerializer) nestedSerializers[0]); } } private void writeObject(ObjectOutputStream outputStream) throws IOException { try (SingleThreadAccessCheck ignored = singleThreadAccessChecker.startSingleThreadAccessCheck()) { outputStream.defaultWriteObject(); } } private static class SingleThreadAccessChecker implements Serializable { private static final long serialVersionUID = 131020282727167064L; private transient AtomicReference currentThreadRef = new AtomicReference<>(); SingleThreadAccessCheck startSingleThreadAccessCheck() { assert(currentThreadRef.compareAndSet(null, Thread.currentThread())) : "The checker has concurrent access from " + currentThreadRef.get(); return new SingleThreadAccessCheck(currentThreadRef); } private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { inputStream.defaultReadObject(); currentThreadRef = new AtomicReference<>(); } } private static class SingleThreadAccessCheck implements AutoCloseable { private final AtomicReference currentThreadRef; private SingleThreadAccessCheck(AtomicReference currentThreadRef) { this.currentThreadRef = currentThreadRef; } @Override public void close() { assert(currentThreadRef.compareAndSet(Thread.currentThread(), null)) : "The checker has concurrent access from " + currentThreadRef.get(); } } } |
blob | blob, long method | t | t | t | long method | 0 | 12584 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/SingleThreadAccessCheckingTypeSerializer.java/#L31-L203 | 1 | 1961 | 12584 | minor | |
| 160 | { "message": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Car2 { @Id private String numberPlate; private String colour; private int engineSize; private int numberOfSeats; public String getNumberPlate() { return numberPlate; } public void setNumberPlate(String numberPlate) { this.numberPlate = numberPlate; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } } |
data class | 1. data class | t | t | t | 0 | 1985 | https://github.com/apache/aries-jpa/blob/f8a04dfabbf0853af07926e4d8f8028b0d829bc8/itests/jpa-container-testbundle-eclipselink/src/main/java/org/apache/aries/jpa/container/itest/eclipselink/entities/Car2.java/#L24-L68 | 1 | 160 | 1985 | major | ||
| 5419 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class HFileBlockDefaultEncodingContext implements HFileBlockEncodingContext { private BlockType blockType; private final DataBlockEncoding encodingAlgo; private byte[] dummyHeader; // Compression state /** Compressor, which is also reused between consecutive blocks. */ private Compressor compressor; /** Compression output stream */ private CompressionOutputStream compressionStream; /** Underlying stream to write compressed bytes to */ private ByteArrayOutputStream compressedByteStream; private HFileContext fileContext; private TagCompressionContext tagCompressionContext; // Encryption state /** Underlying stream to write encrypted bytes to */ private ByteArrayOutputStream cryptoByteStream; /** Initialization vector */ private byte[] iv; private EncodingState encoderState; /** * @param encoding encoding used * @param headerBytes dummy header bytes * @param fileContext HFile meta data */ public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes, HFileContext fileContext) { this.encodingAlgo = encoding; this.fileContext = fileContext; Compression.Algorithm compressionAlgorithm = fileContext.getCompression() == null ? NONE : fileContext.getCompression(); if (compressionAlgorithm != NONE) { compressor = compressionAlgorithm.getCompressor(); compressedByteStream = new ByteArrayOutputStream(); try { compressionStream = compressionAlgorithm.createPlainCompressionStream( compressedByteStream, compressor); } catch (IOException e) { throw new RuntimeException( "Could not create compression stream for algorithm " + compressionAlgorithm, e); } } Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { cryptoByteStream = new ByteArrayOutputStream(); iv = new byte[cryptoContext.getCipher().getIvLength()]; new SecureRandom().nextBytes(iv); } dummyHeader = Preconditions.checkNotNull(headerBytes, "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes"); } /** * prepare to start a new encoding. * @throws IOException */ public void prepareEncoding(DataOutputStream out) throws IOException { if (encodingAlgo != null && encodingAlgo != DataBlockEncoding.NONE) { encodingAlgo.writeIdInBytes(out); } } @Override public void postEncoding(BlockType blockType) throws IOException { this.blockType = blockType; } @Override public Bytes compressAndEncrypt(byte[] data, int offset, int length) throws IOException { return compressAfterEncoding(data, offset, length, dummyHeader); } private Bytes compressAfterEncoding(byte[] uncompressedBytesWithHeaderBuffer, int uncompressedBytesWithHeaderOffset, int uncompressedBytesWithHeaderLength, byte[] headerBytes) throws IOException { Encryption.Context cryptoContext = fileContext.getEncryptionContext(); if (cryptoContext != Encryption.Context.NONE) { // Encrypted block format: // +--------------------------+ // | byte iv length | // +--------------------------+ // | iv data ... | // +--------------------------+ // | encrypted block data ... | // +--------------------------+ cryptoByteStream.reset(); // Write the block header (plaintext) cryptoByteStream.write(headerBytes); InputStream in; int plaintextLength; // Run any compression before encryption if (fileContext.getCompression() != Compression.Algorithm.NONE) { compressedByteStream.reset(); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); byte[] plaintext = compressedByteStream.toByteArray(); plaintextLength = plaintext.length; in = new ByteArrayInputStream(plaintext); } else { plaintextLength = uncompressedBytesWithHeaderLength - headerBytes.length; in = new ByteArrayInputStream(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, plaintextLength); } if (plaintextLength > 0) { // Set up the cipher Cipher cipher = cryptoContext.getCipher(); Encryptor encryptor = cipher.getEncryptor(); encryptor.setKey(cryptoContext.getKey()); // Set up the IV int ivLength = iv.length; Preconditions.checkState(ivLength <= Byte.MAX_VALUE, "IV length out of range"); cryptoByteStream.write(ivLength); if (ivLength > 0) { encryptor.setIv(iv); cryptoByteStream.write(iv); } // Encrypt the data Encryption.encrypt(cryptoByteStream, in, encryptor); // Increment the IV given the final block size Encryption.incrementIv(iv, 1 + (cryptoByteStream.size() / encryptor.getBlockSize())); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } else { cryptoByteStream.write(0); return new Bytes(cryptoByteStream.getBuffer(), 0, cryptoByteStream.size()); } } else { if (this.fileContext.getCompression() != NONE) { compressedByteStream.reset(); compressedByteStream.write(headerBytes); compressionStream.resetState(); compressionStream.write(uncompressedBytesWithHeaderBuffer, headerBytes.length + uncompressedBytesWithHeaderOffset, uncompressedBytesWithHeaderLength - headerBytes.length); compressionStream.flush(); compressionStream.finish(); return new Bytes(compressedByteStream.getBuffer(), 0, compressedByteStream.size()); } else { return null; } } } @Override public BlockType getBlockType() { return blockType; } /** * Releases the compressor this writer uses to compress blocks into the * compressor pool. */ @Override public void close() { if (compressor != null) { this.fileContext.getCompression().returnCompressor(compressor); compressor = null; } } @Override public DataBlockEncoding getDataBlockEncoding() { return this.encodingAlgo; } @Override public HFileContext getHFileContext() { return this.fileContext; } public TagCompressionContext getTagCompressionContext() { return tagCompressionContext; } public void setTagCompressionContext(TagCompressionContext tagCompressionContext) { this.tagCompressionContext = tagCompressionContext; } @Override public EncodingState getEncodingState() { return this.encoderState; } @Override public void setEncodingState(EncodingState state) { this.encoderState = state; } } |
data class | data class, long method | t | t | t | long method | 0 | 15209 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/HFileBlockDefaultEncodingContext.java/#L49-L263 | 1 | 5419 | 15209 | minor | |
| 1746 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11853 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 1746 | 11853 | minor | |
| 938 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method, blob | t | t | t | blob | 0 | 8427 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 938 | 8427 | minor | |
| 2503 | { "response": "YES, I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | data class | t | t | t | 0 | 14665 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 1 | 2503 | 14665 | major | ||
| 502 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method | t | t | t | 0 | 5087 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 502 | 5087 | major | ||
| 339 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class LdapProtocolUtils { /** A delimiter for the replicaId */ public static final String COOKIE_DELIM = ","; /** the prefix for replicaId value */ public static final String REPLICA_ID_PREFIX = "rid="; public static final int REPLICA_ID_PREFIX_LEN = REPLICA_ID_PREFIX.length(); /** the prefix for Csn value */ public static final String CSN_PREFIX = "csn="; private static final int CSN_PREFIX_LEN = CSN_PREFIX.length(); private static final Logger LOG = LoggerFactory.getLogger( LdapProtocolUtils.class ); private LdapProtocolUtils() { } /** * Extracts request controls from a request to populate into an * OperationContext. * * @param opContext the context to populate with request controls * @param request the request to extract controls from */ public static void setRequestControls( OperationContext opContext, Request request ) { if ( request.getControls() != null ) { opContext .addRequestControls( request.getControls().values().toArray( LdapProtocolConstants.EMPTY_CONTROLS ) ); } } /** * Extracts response controls from a an OperationContext to populate into * a Response object. * * @param opContext the context to extract controls from * @param response the response to populate with response controls */ public static void setResponseControls( OperationContext opContext, Response response ) { response.addAllControls( opContext.getResponseControls() ); } public static byte[] createCookie( int replicaId, String csn ) { // the syncrepl cookie format (compatible with OpenLDAP) // rid=nn,csn=xxxz String replicaIdStr = StringUtils.leftPad( Integer.toString( replicaId ), 3, '0' ); return Strings.getBytesUtf8( REPLICA_ID_PREFIX + replicaIdStr + COOKIE_DELIM + CSN_PREFIX + csn ); } /** * Check the cookie syntax. A cookie must have the following syntax : * { rid={replicaId},csn={CSN} } * * @param cookieString The cookie * @return true if the cookie is valid */ public static boolean isValidCookie( String cookieString ) { if ( ( cookieString == null ) || ( cookieString.trim().length() == 0 ) ) { return false; } int pos = cookieString.indexOf( COOKIE_DELIM ); // position should start from REPLICA_ID_PREFIX_LEN or higher cause a cookie can be // like "rid=0,csn={csn}" or "rid=11,csn={csn}" if ( pos <= REPLICA_ID_PREFIX_LEN ) { return false; } String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, pos ); try { Integer.parseInt( replicaId ); } catch ( NumberFormatException e ) { LOG.debug( "Failed to parse the replica id {}", replicaId ); return false; } if ( pos == cookieString.length() ) { return false; } String csnString = cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); return Csn.isValid( csnString ); } /** * returns the CSN present in cookie * * @param cookieString the cookie * @return The CSN */ public static String getCsn( String cookieString ) { int pos = cookieString.indexOf( COOKIE_DELIM ); return cookieString.substring( pos + 1 + CSN_PREFIX_LEN ); } /** * returns the replica id present in cookie * * @param cookieString the cookie * @return The replica Id */ public static int getReplicaId( String cookieString ) { String replicaId = cookieString.substring( REPLICA_ID_PREFIX_LEN, cookieString.indexOf( COOKIE_DELIM ) ); return Integer.parseInt( replicaId ); } } |
blob | long method, blob | t | t | f | long method | blob | 0 | 3490 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolUtils.java/#L38-L171 | 1 | 339 | 3490 | minor |
| 1440 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setVersions(final VersionTag versionTag) { this.memberId = versionTag.getMemberID(); int eVersion = versionTag.getEntryVersion(); this.entryVersionLowBytes = (short) (eVersion & 0xffff); this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16); this.regionVersionHighBytes = versionTag.getRegionVersionHighBytes(); this.regionVersionLowBytes = versionTag.getRegionVersionLowBytes(); if (!versionTag.isGatewayTag() && this.distributedSystemId == versionTag.getDistributedSystemId()) { if (getVersionTimeStamp() <= versionTag.getVersionTimeStamp()) { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } else { versionTag.setVersionTimeStamp(getVersionTimeStamp()); } } else { setVersionTimeStamp(versionTag.getVersionTimeStamp()); } this.distributedSystemId = (byte) (versionTag.getDistributedSystemId() & 0xff); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 10972 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/entries/VersionedStatsRegionEntryOffHeapIntKey.java/#L287-L306 | 2 | 1440 | 10972 | minor | |
| 2097 | {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 13149 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 1 | 2097 | 13149 | minor |
| 2087 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 13106 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 1 | 2087 | 13106 | major | ||
| 640 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static boolean isBelowLoadLevel(SystemResourceUsage usage, float thresholdPercentage) { return (usage.bandwidthOut.percentUsage() < thresholdPercentage && usage.bandwidthIn.percentUsage() < thresholdPercentage && usage.cpu.percentUsage() < thresholdPercentage && usage.directMemory.percentUsage() < thresholdPercentage); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6350 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/SimpleLoadManagerImpl.java/#L1069-L1074 | 2 | 640 | 6350 | major | |
| 1710 | YES, I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11765 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 1710 | 11765 | major | |
| 2100 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1. long method | t | t | f | long method | 0 | 13158 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 2100 | 13158 | minor | |
| 5561 | YES I found bad smells the bad smells are listed in this format: 1. Long method, 2. Data class, 3. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2 Data class, 3 Feature envy | t | f | t | 2. Data class, 3. Feature envy | 0 | 7769 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5561 | 7769 | minor | |
| 1850 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LuceneIndexForPartitionedRegion extends LuceneIndexImpl { protected Region fileAndChunkRegion; protected final FileSystemStats fileSystemStats; public static final String FILES_REGION_SUFFIX = ".files"; private final ExecutorService waitingThreadPoolFromDM; public LuceneIndexForPartitionedRegion(String indexName, String regionPath, InternalCache cache) { super(indexName, regionPath, cache); this.waitingThreadPoolFromDM = cache.getDistributionManager().getWaitingThreadPool(); final String statsName = indexName + "-" + regionPath; this.fileSystemStats = new FileSystemStats(cache.getDistributedSystem(), statsName); } @Override protected RepositoryManager createRepositoryManager(LuceneSerializer luceneSerializer) { LuceneSerializer mapper = luceneSerializer; if (mapper == null) { mapper = new HeterogeneousLuceneSerializer(); } PartitionedRepositoryManager partitionedRepositoryManager = new PartitionedRepositoryManager(this, mapper, this.waitingThreadPoolFromDM); return partitionedRepositoryManager; } @Override public boolean isIndexingInProgress() { PartitionedRegion userRegion = (PartitionedRegion) cache.getRegion(this.getRegionPath()); Set fileRegionPrimaryBucketIds = this.getFileAndChunkRegion().getDataStore().getAllLocalPrimaryBucketIds(); for (Integer bucketId : fileRegionPrimaryBucketIds) { BucketRegion userBucket = userRegion.getDataStore().getLocalBucketById(bucketId); if (!userBucket.isEmpty() && !this.isIndexAvailable(bucketId)) { return true; } } return false; } @Override protected void createLuceneListenersAndFileChunkRegions( PartitionedRepositoryManager partitionedRepositoryManager) { partitionedRepositoryManager.setUserRegionForRepositoryManager((PartitionedRegion) dataRegion); RegionShortcut regionShortCut; final boolean withPersistence = withPersistence(); RegionAttributes regionAttributes = dataRegion.getAttributes(); final boolean withStorage = regionAttributes.getPartitionAttributes().getLocalMaxMemory() > 0; // TODO: 1) dataRegion should be withStorage // 2) Persistence to Persistence // 3) Replicate to Replicate, Partition To Partition // 4) Offheap to Offheap if (!withStorage) { regionShortCut = RegionShortcut.PARTITION_PROXY; } else if (withPersistence) { // TODO: add PartitionedRegionAttributes instead regionShortCut = RegionShortcut.PARTITION_PERSISTENT; } else { regionShortCut = RegionShortcut.PARTITION; } // create PR fileAndChunkRegion, but not to create its buckets for now final String fileRegionName = createFileRegionName(); PartitionAttributes partitionAttributes = dataRegion.getPartitionAttributes(); DistributionManager dm = this.cache.getInternalDistributedSystem().getDistributionManager(); LuceneBucketListener lucenePrimaryBucketListener = new LuceneBucketListener(partitionedRepositoryManager, dm); if (!fileRegionExists(fileRegionName)) { fileAndChunkRegion = createRegion(fileRegionName, regionShortCut, this.regionPath, partitionAttributes, regionAttributes, lucenePrimaryBucketListener); } fileSystemStats .setBytesSupplier(() -> getFileAndChunkRegion().getPrStats().getDataStoreBytesInUse()); } public PartitionedRegion getFileAndChunkRegion() { return (PartitionedRegion) fileAndChunkRegion; } public FileSystemStats getFileSystemStats() { return fileSystemStats; } boolean fileRegionExists(String fileRegionName) { return cache.getRegion(fileRegionName) != null; } public String createFileRegionName() { return LuceneServiceImpl.getUniqueIndexRegionName(indexName, regionPath, FILES_REGION_SUFFIX); } private PartitionAttributesFactory configureLuceneRegionAttributesFactory( PartitionAttributesFactory attributesFactory, PartitionAttributes dataRegionAttributes) { attributesFactory.setTotalNumBuckets(dataRegionAttributes.getTotalNumBuckets()); attributesFactory.setRedundantCopies(dataRegionAttributes.getRedundantCopies()); attributesFactory.setPartitionResolver(getPartitionResolver(dataRegionAttributes)); attributesFactory.setRecoveryDelay(dataRegionAttributes.getRecoveryDelay()); attributesFactory.setStartupRecoveryDelay(dataRegionAttributes.getStartupRecoveryDelay()); return attributesFactory; } private PartitionResolver getPartitionResolver(PartitionAttributes dataRegionAttributes) { if (dataRegionAttributes.getPartitionResolver() instanceof FixedPartitionResolver) { return new BucketTargetingFixedResolver(); } else { return new BucketTargetingResolver(); } } protected Region createRegion(final String regionName, final RegionShortcut regionShortCut, final String colocatedWithRegionName, final PartitionAttributes partitionAttributes, final RegionAttributes regionAttributes, PartitionListener lucenePrimaryBucketListener) { PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory(); if (lucenePrimaryBucketListener != null) { partitionAttributesFactory.addPartitionListener(lucenePrimaryBucketListener); } partitionAttributesFactory.setColocatedWith(colocatedWithRegionName); configureLuceneRegionAttributesFactory(partitionAttributesFactory, partitionAttributes); // Create AttributesFactory based on input RegionShortcut RegionAttributes baseAttributes = this.cache.getRegionAttributes(regionShortCut.toString()); AttributesFactory factory = new AttributesFactory(baseAttributes); factory.setPartitionAttributes(partitionAttributesFactory.create()); if (regionAttributes.getDataPolicy().withPersistence()) { factory.setDiskStoreName(regionAttributes.getDiskStoreName()); } RegionAttributes attributes = factory.create(); return createRegion(regionName, attributes); } public void close() {} @Override public void dumpFiles(final String directory) { ResultCollector results = FunctionService.onRegion(getDataRegion()) .setArguments(new String[] {directory, indexName}).execute(DumpDirectoryFiles.ID); results.getResult(); } @Override public void destroy(boolean initiator) { if (logger.isDebugEnabled()) { logger.debug("Destroying index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } // Invoke super destroy to remove the extension and async event queue super.destroy(initiator); // Destroy index on remote members if necessary if (initiator) { destroyOnRemoteMembers(); } // Destroy the file region (colocated with the application region) if necessary // localDestroyRegion can't be used because locally destroying regions is not supported on // colocated regions if (initiator) { try { fileAndChunkRegion.destroyRegion(); if (logger.isDebugEnabled()) { logger.debug("Destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Already destroyed fileAndChunkRegion=" + fileAndChunkRegion.getName()); } } } if (logger.isDebugEnabled()) { logger.debug("Destroyed index regionPath=" + regionPath + "; indexName=" + indexName + "; initiator=" + initiator); } } @Override public boolean isIndexAvailable(int id) { PartitionedRegion fileAndChunkRegion = getFileAndChunkRegion(); return (fileAndChunkRegion.get(IndexRepositoryFactory.APACHE_GEODE_INDEX_COMPLETE, id) != null || !LuceneServiceImpl.LUCENE_REINDEX); } private void destroyOnRemoteMembers() { DistributionManager dm = getDataRegion().getDistributionManager(); Set recipients = dm.getOtherNormalDistributionManagerIds(); if (!recipients.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: About to send destroy message recipients=" + recipients); } ReplyProcessor21 processor = new ReplyProcessor21(dm, recipients); DestroyLuceneIndexMessage message = new DestroyLuceneIndexMessage(recipients, processor.getProcessorId(), regionPath, indexName); dm.putOutgoing(message); if (logger.isDebugEnabled()) { logger.debug("LuceneIndexForPartitionedRegion: Sent message recipients=" + recipients); } try { processor.waitForReplies(); } catch (ReplyException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // If the IllegalArgumentException is index not found, then its ok; otherwise rethrow it. String fullRegionPath = regionPath.startsWith(Region.SEPARATOR) ? regionPath : Region.SEPARATOR + regionPath; String indexNotFoundMessage = String.format("Lucene index %s was not found in region %s", indexName, fullRegionPath); if (!cause.getLocalizedMessage().equals(indexNotFoundMessage)) { throw e; } } else if (!(cause instanceof CancelException)) { throw e; } } catch (InterruptedException e) { dm.getCancelCriterion().checkCancelInProgress(e); Thread.currentThread().interrupt(); } } } } |
blob | 1 Long Method, 2 Blob | t | f | t | 1. Long Method | 0 | 12188 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/LuceneIndexForPartitionedRegion.java/#L49-L277 | 1 | 1850 | 12188 | major | |
| 337 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SQLDropTableStatement extends SQLStatementImpl implements SQLDropStatement { private List hints; protected List tableSources = new ArrayList(); private boolean purge; protected boolean cascade = false; protected boolean restrict = false; protected boolean ifExists = false; private boolean temporary = false; public SQLDropTableStatement(){ } public SQLDropTableStatement(String dbType){ super (dbType); } public SQLDropTableStatement(SQLName name, String dbType){ this(new SQLExprTableSource(name), dbType); } public SQLDropTableStatement(SQLName name){ this (name, null); } public SQLDropTableStatement(SQLExprTableSource tableSource){ this (tableSource, null); } public SQLDropTableStatement(SQLExprTableSource tableSource, String dbType){ this (dbType); this.tableSources.add(tableSource); } public List getTableSources() { return tableSources; } public void addPartition(SQLExprTableSource tableSource) { if (tableSource != null) { tableSource.setParent(this); } this.tableSources.add(tableSource); } public void setName(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLName name) { this.addTableSource(new SQLExprTableSource(name)); } public void addTableSource(SQLExprTableSource tableSource) { tableSources.add(tableSource); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, tableSources); } visitor.endVisit(this); } @Override public List getChildren() { return this.tableSources; } public boolean isPurge() { return purge; } public void setPurge(boolean purge) { this.purge = purge; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean isCascade() { return cascade; } public void setCascade(boolean cascade) { this.cascade = cascade; } public boolean isRestrict() { return restrict; } public void setRestrict(boolean restrict) { this.restrict = restrict; } public boolean isTemporary() { return temporary; } public void setTemporary(boolean temporary) { this.temporary = temporary; } public List getHints() { return hints; } public void setHints(List hints) { this.hints = hints; } } |
data class | data class | t | t | t | 0 | 3472 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTableStatement.java/#L26-L146 | 1 | 337 | 3472 | major | ||
| 2241 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | 1. long method | t | t | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 1 | 2241 | 13621 | critical | ||
| 1132 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | 1. long method | t | t | t | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 1 | 1132 | 10040 | minor | ||
| 3968 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10409 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 3968 | 10409 | critical | ||
| 1701 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, data class | t | t | t | long method | 0 | 11736 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 1701 | 11736 | critical | |
| 570 | { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. * @return list of VMInstanceVO running on that host. */ List listByHostId(long hostId); /** * List VMs by zone ID * @param zoneId * @return list of VMInstanceVO in the specified zone */ List listByZoneId(long zoneId); /** * List VMs by pod ID * @param podId * @return list of VMInstanceVO in the specified pod */ List listByPodId(long podId); /** * Lists non-expunged VMs by templateId * @param templateId * @return list of VMInstanceVO deployed from the specified template, that are not expunged */ public List listNonExpungedByTemplate(long templateId); /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged */ public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId); /** * Find vm instance with names like. * * @param name name that fits SQL like. * @return list of VMInstanceVO */ List findVMInstancesLike(String name); List findVMInTransition(Date time, State... states); List listByHostAndState(long hostId, State... states); List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); VMInstanceVO findVMByInstanceName(String name); VMInstanceVO findVMByHostName(String hostName); void updateProxyId(long id, Long proxyId, Date time); List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public List findIdsOfAllocatedVirtualRoutersForAccount(long accountId); List listByClusterId(long clusterId); // this does not pull up VMs which are starting List listLHByClusterId(long clusterId); // get all the VMs even starting one on this cluster List listVmsMigratingFromHost(Long hostId); public Long countActiveByHostId(long hostId); Pair, Map> listClusterIdsInZoneByVmCount(long zoneId, long accountId); Pair, Map> listClusterIdsInPodByVmCount(long podId, long accountId); Pair, Map> listPodIdsInZoneByVmCount(long dataCenterId, long accountId); List listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId); Long countRunningByAccount(long accountId); Long countByZoneAndState(long zoneId, State state); List listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types); /** * @param networkId * @param types * @return */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState); void resetVmPowerStateTracking(long instanceId); void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); boolean isPowerStateUpToDate(long instanceId); List listNonMigratingVmsByHostEqualsLastHost(long hostId); } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 5736 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java/#L34-L155 | 1 | 570 | 5736 | minor | |
| 2535 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 2535 | 14753 | minor | ||
| 4048 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Primitive obsession 4. Data class 5. Message chains 6. Feature envy 7. Inappropriate intimacy (calling methods from parent class) 8. Mixed levels of abstraction 9. Code repetition (multiple use of "dis" variable) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | Long method2 Long parameter list3 Primitive obsession4 Data class5 Message chains6 Feature envy7 Inappropriate intimacy (calling methods from parent class)8 Mixed levels of abstraction9 Code repetition (multiple use of "dis" variable) | t | f | t | 0 | 10697 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 2 | 4048 | 10697 | critical | ||
| 4040 | YES I found bad smells.the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10682 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 4040 | 10682 | major | ||
| 2132 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 2132 | 13234 | minor | ||
| 649 | YES I found bad smells the bad smells are: 1. Long method 2. Conditional complexity 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: CompletableFuture getLastMessageIdAsync() { if (getState() == State.Closing || getState() == State.Closed) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Consumer was already closed")); } AtomicLong opTimeoutMs = new AtomicLong(client.getConfiguration().getOperationTimeoutMs()); Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, opTimeoutMs.get() * 2, TimeUnit.MILLISECONDS, 0 , TimeUnit.MILLISECONDS); CompletableFuture getLastMessageIdFuture = new CompletableFuture<>(); internalGetLastMessageIdAsync(backoff, opTimeoutMs, getLastMessageIdFuture); return getLastMessageIdFuture; } |
feature envy | Long method2 Conditional complexity3 Feature envy | t | f | t | 0 | 6382 | https://github.com/apache/pulsar/blob/044daf8d61328265640a5b3e5008fc04fac73efa/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java/#L1442-L1456 | 2 | 649 | 6382 | major | ||
| 2146 | {"response": "YES, I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | 1. data class | t | t | f | data class | 0 | 13275 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 2146 | 13275 | major | |
| 658 | {"output": "YES I found bad smells\nthe bad smells are: 1. Long Method, 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 6413 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 1 | 658 | 6413 | critical | |
| 1835 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 12133 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 1 | 1835 | 12133 | minor | |
| 1328 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | data class | t | t | t | 0 | 10705 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 1 | 1328 | 10705 | critical | ||
| 4708 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | Long Method | t | f | t | 0 | 12628 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 4708 | 12628 | minor | ||
| 2419 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method, feature envy | t | t | t | feature envy | 0 | 14427 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 2419 | 14427 | minor | |
| 2340 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | long method | t | t | t | 0 | 14174 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 1 | 2340 | 14174 | minor | ||
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 1 | 169 | 2032 | minor | ||
| 2431 | with defined inputs. * * * * @param airavataExperimentId * * @param gatewayId * * @param experiment * * "./src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeResourceResource.java" YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14458 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 2431 | 14458 | minor | ||
| 845 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | 1: long method | t | t | t | 0 | 7823 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 845 | 7823 | minor | ||
| 805 | {"response": "YES I found bad smells", "bad smells": ["Long Method", "Data Class", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class VideoProducerImplementation extends HandlerBase implements IVideoProducer { private VideoProducer videoParams; private Framebuffer fbo; private FloatBuffer depthBuffer; @Override public boolean parseParameters(Object params) { if (params == null || !(params instanceof VideoProducer)) return false; this.videoParams = (VideoProducer) params; return true; } @Override public VideoType getVideoType() { return VideoType.VIDEO; } @Override public void getFrame(MissionInit missionInit, ByteBuffer buffer) { if (!this.videoParams.isWantDepth()) { getRGBFrame(buffer); // Just return the simple RGB, 3bpp image. return; } // Otherwise, do the work of extracting the depth map: final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, this.fbo.framebufferObject); GL30.glBlitFramebuffer(0, 0, Minecraft.getMinecraft().getFramebuffer().framebufferWidth, Minecraft.getMinecraft().getFramebuffer().framebufferHeight, 0, 0, width, height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); this.fbo.bindFramebuffer(true); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, this.depthBuffer); this.fbo.unbindFramebuffer(); // Now convert the depth buffer into values from 0-255 and copy it over // the alpha channel. // We either use the min and max values supplied in order to scale it, // or we scale it according // to the dynamic content: float minval, maxval; // The scaling section is optional (since the depthmap is optional) - so // if there is no depthScaling object, // go with the default of autoscale. if (this.videoParams.getDepthScaling() == null || this.videoParams.getDepthScaling().isAutoscale()) { minval = 1; maxval = 0; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); if (f < minval) minval = f; if (f > maxval) maxval = f; } } else { minval = this.videoParams.getDepthScaling().getMin().floatValue(); maxval = this.videoParams.getDepthScaling().getMax().floatValue(); if (minval > maxval) { // You can't trust users. float t = minval; minval = maxval; maxval = t; } } float range = maxval - minval; if (range < 0.000001) range = 0.000001f; // To avoid divide by zero errors in cases where // there is no depth variance float scale = 255 / range; for (int i = 0; i < width * height; i++) { float f = this.depthBuffer.get(i); f = (f < minval ? minval : (f > maxval ? maxval : f)); f -= minval; f *= scale; buffer.put(i * 4 + 3, (byte) f); } // Reset depth buffer ready for next read: this.depthBuffer.clear(); } @Override public int getWidth() { return this.videoParams.getWidth(); } @Override public int getHeight() { return this.videoParams.getHeight(); } public int getRequiredBufferSize() { return this.videoParams.getWidth() * this.videoParams.getHeight() * (this.videoParams.isWantDepth() ? 4 : 3); } private void getRGBFrame(ByteBuffer buffer) { final int format = GL_RGB; final int width = this.videoParams.getWidth(); final int height = this.videoParams.getHeight(); // Render the Minecraft frame into our own FBO, at the desired size: this.fbo.bindFramebuffer(true); Minecraft.getMinecraft().getFramebuffer().framebufferRenderExt(width, height, true); // Now read the pixels out from that: // glReadPixels appears to be faster than doing: // GlStateManager.bindTexture(this.fbo.framebufferTexture); // GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, // buffer); glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, buffer); this.fbo.unbindFramebuffer(); GlStateManager.enableDepth(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } @Override public void prepare(MissionInit missionInit) { this.fbo = new Framebuffer(this.videoParams.getWidth(), this.videoParams.getHeight(), true); // Create a buffer for retrieving the depth map, if requested: if (this.videoParams.isWantDepth()) this.depthBuffer = BufferUtils.createFloatBuffer(this.videoParams.getWidth() * this.videoParams.getHeight()); // Set the requested camera position Minecraft.getMinecraft().gameSettings.thirdPersonView = this.videoParams.getViewpoint(); } @Override public void cleanup() { this.fbo.deleteFramebuffer(); // Must do this or we leak resources. } } |
blob | long method, data class, blob | t | t | t | long method, data class | 0 | 7623 | https://github.com/Microsoft/malmo/blob/91b1a7a01ec0dd883f81a51048badac0398695f7/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/VideoProducerImplementation.java/#L44-L193 | 1 | 805 | 7623 | minor | |
| 1418 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10924 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1418 | 10924 | minor | ||
| 1765 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class BaseColumnInfo implements Serializable { /** * Serial version id. */ private static final long serialVersionUID = 1L; /** * The table and alias info encapsulated in a different class. */ private TableAliasInfo tabAlias; /** * The metastore column information. The column can be null * and that denotes that the expression is dependent on the row * of the table and not particular column. This can happen in case * of count(1). */ private FieldSchema column; /** * @return the tabAlias */ public TableAliasInfo getTabAlias() { return tabAlias; } /** * @param tabAlias the tabAlias to set */ public void setTabAlias(TableAliasInfo tabAlias) { this.tabAlias = tabAlias; } /** * @return the column */ public FieldSchema getColumn() { return column; } /** * @param column the column to set */ public void setColumn(FieldSchema column) { this.column = column; } @Override public String toString() { return tabAlias + ":" + column; } @Override public int hashCode() { return (column != null ? column.hashCode() : 7) + (tabAlias != null ? tabAlias.hashCode() : 11); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BaseColumnInfo)) { return false; } BaseColumnInfo ci = (BaseColumnInfo) obj; return (column == null ? ci.column == null : column.equals(ci.column)) && (tabAlias == null ? ci.tabAlias == null : tabAlias.equals(ci.tabAlias)); } } |
data class | Data Class | t | f | t | 0 | 11903 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/hooks/LineageInfo.java/#L217-L288 | 1 | 1765 | 11903 | minor | ||
| 4314 | { "output": "YES I found bad smells", "detected bad smells": [ "1. Blob", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 11368 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 1 | 4314 | 11368 | minor | |
| 2209 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.LimitedPrivate({"MapReduce"}) @InterfaceStability.Unstable public static class Context { private final MapTask mapTask; private final JobConf jobConf; private final TaskReporter reporter; public Context(MapTask mapTask, JobConf jobConf, TaskReporter reporter) { this.mapTask = mapTask; this.jobConf = jobConf; this.reporter = reporter; } public MapTask getMapTask() { return mapTask; } public JobConf getJobConf() { return jobConf; } public TaskReporter getReporter() { return reporter; } } |
data class | data class | t | t | t | 0 | 13518 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MapOutputCollector.java/#L40-L64 | 1 | 2209 | 13518 | minor | ||
| 728 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | Long method,2 Feature envy | t | f | t | . Long method | 0 | 6853 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 728 | 6853 | major | |
| 2651 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | data class, long method | t | t | t | long method | 0 | 15170 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 2651 | 15170 | critical | |
| 5744 | YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 1 | 5744 | 14137 | minor | |
| 2077 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "SerializationRegistrationType", "2. Data Class": "Serializer", "3. Data Class": "Instantiator" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | 1. long method: serializationregistrationtype, 2. data class: serializer, 3. data class: instantiator | t | t | f | 1. long method: serializationregistrationtype | data class | 0 | 13052 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 2077 | 13052 | major |
| 1860 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | 1. long method | t | t | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 1860 | 12221 | minor | ||
| 1348 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method | t | t | t | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 1348 | 10753 | minor | ||
| 966 | YES, I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 2 | 966 | 8633 | minor | ||
| 1744 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Conditional complexity 5. Inconsistent naming convention 6. Confusing variable names 7. Lack of comments/documentation 8. Use of magic numbers or strings | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long method2 Feature envy3 Duplicated code4 Conditional complexity 5 Inconsistent naming convention 6 Confusing variable names 7 Lack of comments/documentation 8 Use of magic numbers or strings | t | f | t | 0 | 11849 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 1744 | 11849 | major | ||
| 102 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
data class | data class | t | t | t | 0 | 1315 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 102 | 1315 | minor | ||
| 5324 | YES I found bad smells The bad smells are: 1.Feature envy 2.Long method 3.Inconsistent spacing and indentation 4.Magic numbers (PigConfiguration.PIG_ATS_ENABLED) 5.Multiple conditionals in one line (Boolean.parseBoolean calls) 6.Coupled classes (PigATSClient) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Feature envy2Long method3Inconsistent spacing and indentation4Magic numbers (PigConfigurationPIG_ATS_ENABLED)5Multiple conditionals in one line (BooleanparseBoolean calls)6Coupled classes (PigATSClient) | t | f | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 5324 | 14946 | major | ||
| 1861 | { "output": "YES, I did find bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method | t | t | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1861 | 12222 | minor | ||
| 3875 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | 1. data class | t | t | t | 0 | 10123 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 1 | 3875 | 10123 | major | ||
| 3707 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method, 2Feature envy, 3Magic number, 4Throws declaration, 5Overutilization of try-catch blocks, 6Duplicate code, 7Potentially unnecessary variable assignment, 8Inconsistent naming conventions | t | f | t | 2.Feature envy, 3.Magic number, 4.Throws declaration, 5.Overutilization of try-catch blocks, 6.Duplicate code, 7.Potentially unnecessary variable assignment, 8.Inconsistent naming conventions. | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 3707 | 8853 | minor | |
| 4334 | YES We found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11444 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 2 | 4334 | 11444 | minor | ||
| 2319 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long method", "2. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SequenceFileReader extends AbstractFileReader { public static final String[] defaultFields = { "key", "value" }; public static final String BUFFER_SIZE = "hdfsspout.reader.buffer.bytes"; private static final Logger LOG = LoggerFactory .getLogger(SequenceFileReader.class); private static final int DEFAULT_BUFF_SIZE = 4096; private final SequenceFile.Reader reader; private final SequenceFileReader.Offset offset; private final Key key; private final Value value; public SequenceFileReader(FileSystem fs, Path file, Map conf) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); this.offset = new SequenceFileReader.Offset(0, 0, 0); } public SequenceFileReader(FileSystem fs, Path file, Map conf, String offset) throws IOException { super(fs, file); int bufferSize = !conf.containsKey(BUFFER_SIZE) ? DEFAULT_BUFF_SIZE : Integer.parseInt(conf.get(BUFFER_SIZE).toString()); this.offset = new SequenceFileReader.Offset(offset); this.reader = new SequenceFile.Reader(fs.getConf(), SequenceFile.Reader.file(file), SequenceFile.Reader.bufferSize(bufferSize)); this.key = (Key) ReflectionUtils.newInstance(reader.getKeyClass(), fs.getConf()); this.value = (Value) ReflectionUtils.newInstance(reader.getValueClass(), fs.getConf()); skipToOffset(this.reader, this.offset, this.key); } private static void skipToOffset(SequenceFile.Reader reader, Offset offset, K key) throws IOException { reader.sync(offset.lastSyncPoint); for (int i = 0; i < offset.recordsSinceLastSync; ++i) { reader.next(key); } } public List next() throws IOException, ParseException { if (reader.next(key, value)) { ArrayList result = new ArrayList(2); Collections.addAll(result, key, value); offset.increment(reader.syncSeen(), reader.getPosition()); return result; } return null; } @Override public void close() { try { reader.close(); } catch (IOException e) { LOG.warn("Ignoring error when closing file " + getFilePath(), e); } } public Offset getFileOffset() { return offset; } public static class Offset implements FileOffset { public long lastSyncPoint; public long recordsSinceLastSync; public long currentRecord; private long currRecordEndOffset; private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if (offset == null) { throw new IllegalArgumentException("offset cannot be null"); } if (offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if (rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord + 1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if (currentRecord < rhs.currentRecord) { return -1; } if (currentRecord == rhs.currentRecord) { return 0; } return 1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Offset)) { return false; } Offset offset = (Offset) o; return currentRecord == offset.currentRecord; } @Override public int hashCode() { return (int) (currentRecord ^ (currentRecord >>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if (!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
blob | 1. long method, 2. blob | t | t | t | 1. long method | 0 | 14125 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/external/storm-hdfs/src/main/java/org/apache/storm/hdfs/spout/SequenceFileReader.java/#L28-L209 | 1 | 2319 | 14125 | minor | |
| 423 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | long method, data class | t | t | t | data class | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 423 | 4247 | major | |
| 642 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 642 | 6353 | critical | ||
| 3075 | YES I found bad smells the bad smells are: 1.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public InstrumentationFacility getInstrumentationFacility() { return getRootContext().getInstrumentationFacility(); } |
feature envy | Feature envy | t | f | t | 0 | 3714 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-core/src/main/java/org/apache/uima/impl/ChildUimaContext_impl.java/#L101-L103 | 2 | 3075 | 3714 | minor | ||
| 544 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | 1. long method | t | t | f | long method | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 544 | 5546 | minor | |
| 975 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | data class | t | t | t | 0 | 8780 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 1 | 975 | 8780 | major | ||
| 1484 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method | t | t | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 1484 | 11088 | major | ||
| 662 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | long method | t | t | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 1 | 662 | 6455 | minor | ||
| 141 | { "response": "YES I found bad smells", "details": { "the bad smells are": [ "Long method" ] } } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | the bad smells are: long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 2 | 141 | 1773 | minor | ||
| 1454 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 1454 | 11007 | minor | ||
| 1180 | YES I found bad smells the bad smells are: 1. Data class, 2. Lazy class, 3. Long methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | Data class, 2 Lazy class, 3 Long methods | t | f | t | 2. Lazy class, 3. Long methods | 0 | 10230 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 2 | 1180 | 10230 | critical | |
| 1764 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @DeferredContextBinding public class RoutesHealthCheckRepository implements CamelContextAware, HealthCheckRepository { private final ConcurrentMap checks; private Set blacklist; private List> evaluators; private ConcurrentMap>> evaluatorMap; private volatile CamelContext context; public RoutesHealthCheckRepository() { this.checks = new ConcurrentHashMap<>(); } @Override public void setCamelContext(CamelContext camelContext) { this.context = camelContext; } @Override public CamelContext getCamelContext() { return context; } public void setBlacklistedRoutes(Collection blacklistedRoutes) { blacklistedRoutes.forEach(this::addBlacklistedRoute); } public void addBlacklistedRoute(String routeId) { if (this.blacklist == null) { this.blacklist = new HashSet<>(); } this.blacklist.add(routeId); } public void setEvaluators(Collection> evaluators) { evaluators.forEach(this::addEvaluator); } public void addEvaluator(PerformanceCounterEvaluator evaluator) { if (this.evaluators == null) { this.evaluators = new CopyOnWriteArrayList<>(); } this.evaluators.add(evaluator); } public void setRoutesEvaluators(Map>> evaluators) { evaluators.forEach(this::setRouteEvaluators); } public void setRouteEvaluators(String routeId, Collection> evaluators) { evaluators.forEach(evaluator -> addRouteEvaluator(routeId, evaluator)); } public void addRouteEvaluator(String routeId, PerformanceCounterEvaluator evaluator) { if (this.evaluatorMap == null) { this.evaluatorMap = new ConcurrentHashMap<>(); } this.evaluatorMap.computeIfAbsent(routeId, id -> new CopyOnWriteArrayList<>()).add(evaluator); } public Stream> evaluators() { return this.evaluators != null ? this.evaluators.stream() : Stream.empty(); } public Stream> evaluators(String routeId) { return this.evaluatorMap != null ? evaluatorMap.getOrDefault(routeId, Collections.emptyList()).stream() : Stream.empty(); } @Override public Stream stream() { // This is not really efficient as getRoutes() creates a copy of the routes // array for each invocation. It would be nice to have more stream oriented // operation on CamelContext i.e. // // interface CamelContext { // // Stream routes(); // // void forEachRoute(Consumer consumer); // } // return this.context != null ? this.context.getRoutes() .stream() .filter(route -> route.getId() != null) .filter(route -> isNotBlacklisted(route)) .map(this::toRouteHealthCheck) : Stream.empty(); } // ***************************** // Helpers // ***************************** private boolean isNotBlacklisted(Route route) { return this.blacklist != null ? !this.blacklist.contains(route.getId()) : true; } private HealthCheck toRouteHealthCheck(Route route) { return checks.computeIfAbsent( route, r -> { HealthCheck check = new RouteHealthCheck( route, evaluatorMap != null ? evaluatorMap.getOrDefault(r.getId(), evaluators) : evaluators ); check.getConfiguration().setEnabled(true); return check; } ); } } |
blob | Blob | t | f | t | 0 | 11900 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/impl/health/RoutesHealthCheckRepository.java/#L38-L161 | 1 | 1764 | 11900 | minor | ||
| 422 | YES I found bad smells" the bad smells are: 1. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Feature envy | t | f | t | 0 | 4246 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 422 | 4246 | minor | ||
| 2594 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return */ public abstract String getExpressionSymbol(); /** * @param expression */ public void setRight(Expression expression) { right = expression; } /** * @param expression */ public void setLeft(Expression expression) { left = expression; } } |
data class | data class, long method | t | t | t | long method | 0 | 15004 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/filter/BinaryExpression.java/#L26-L96 | 1 | 2594 | 15004 | critical | |
| 650 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | long method | t | t | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 1 | 650 | 6383 | minor | ||
| 2222 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class AtlasPerfTracer { protected final Logger logger; protected final String tag; private final long startTimeMs; private static long reportingThresholdMs = 0L; public static Logger getPerfLogger(String name) { return LoggerFactory.getLogger("org.apache.atlas.perf." + name); } public static Logger getPerfLogger(Class cls) { return AtlasPerfTracer.getPerfLogger(cls.getName()); } public static boolean isPerfTraceEnabled(Logger logger) { return logger.isDebugEnabled(); } public static AtlasPerfTracer getPerfTracer(Logger logger, String tag) { return new AtlasPerfTracer(logger, tag); } public static void log(AtlasPerfTracer tracer) { if (tracer != null) { tracer.log(); } } private AtlasPerfTracer(Logger logger, String tag) { this.logger = logger; this.tag = tag; startTimeMs = System.currentTimeMillis(); } public String getTag() { return tag; } public long getStartTime() { return startTimeMs; } public long getElapsedTime() { return System.currentTimeMillis() - startTimeMs; } public void log() { long elapsedTime = getElapsedTime(); if (elapsedTime > reportingThresholdMs) { logger.debug("PERF|{}|{}", tag, elapsedTime); } } } |
data class | data class | t | t | t | 0 | 13559 | https://github.com/apache/atlas/blob/af1719a3472d1d436d0fc685fe9f88d8a754ef94/common/src/main/java/org/apache/atlas/utils/AtlasPerfTracer.java/#L27-L80 | 1 | 2222 | 13559 | minor | ||
| 2308 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | data class, long method | t | t | t | long method | 0 | 14094 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 2308 | 14094 | major | |
| 2564 | { "response": "YES I found bad smells", "detectedBadSmells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14847 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 1 | 2564 | 14847 | minor | ||
| 2241 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13621 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 2241 | 13621 | critical | ||
| 1242 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 10414 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 1 | 1242 | 10414 | minor | |
| 1147 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | long method, data class | t | t | t | data class | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 1147 | 10122 | major | |
| 2689 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class, long method | t | t | t | long method | 0 | 15284 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 2689 | 15284 | major | |
| 2156 | {"message": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
long method | 1. long method | t | t | f | long method | 0 | 13302 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 1 | 2156 | 13302 | major | |
| 1363 | YES I found bad smells the bad smells are: 1.Long method 2.Magic numbers 3.Duplicate code 4.Commented code 5.Inconsistent formatting 6.Lack of proper variable naming 7.Complex conditional statements 8.Multiple responsibilities within one method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2Magic numbers3Duplicate code4Commented code5Inconsistent formatting6Lack of proper variable naming7Complex conditional statements8Multiple responsibilities within one method | t | f | t | 0 | 10780 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1363 | 10780 | major | ||
| 465 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | data class | t | t | t | 0 | 4508 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 465 | 4508 | major | ||
| 2453 | YES I found bad smells The bad smells are: 1. Long method 2. Repetitive code 3. Feature envy 4. Primitive obsession 5. Inappropriate intimate accessor 6. Inconsistent naming convention 7. Poor naming 8. Dead code 9. Data class 10. Large class 11. Complex code 12. Shotgun surgery 13. Inappropriate inheritance 14. Refused bequest | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class NetworkBridgeStatistics extends StatsImpl { protected CountStatisticImpl enqueues; protected CountStatisticImpl dequeues; protected CountStatisticImpl receivedCount; public NetworkBridgeStatistics() { enqueues = new CountStatisticImpl("enqueues", "The current number of enqueues this bridge has, which is the number of potential messages to be forwarded."); dequeues = new CountStatisticImpl("dequeues", "The current number of dequeues this bridge has, which is the number of messages received by the remote broker."); receivedCount = new CountStatisticImpl("receivedCount", "The number of messages that have been received by the NetworkBridge from the remote broker. Only applies for Duplex bridges."); addStatistic("enqueues", enqueues); addStatistic("dequeues", dequeues); addStatistic("receivedCount", receivedCount); } /** * The current number of enqueues this bridge has, which is the number of potential messages to be forwarded * Messages may not be forwarded if there is no subscription * * @return */ public CountStatisticImpl getEnqueues() { return enqueues; } /** * The current number of dequeues this bridge has, which is the number of * messages actually sent to and received by the remote broker. * * @return */ public CountStatisticImpl getDequeues() { return dequeues; } /** * The number of messages that have been received by the NetworkBridge from the remote broker. * Only applies for Duplex bridges. * * @return */ public CountStatisticImpl getReceivedCount() { return receivedCount; } @Override public void reset() { if (this.isDoReset()) { super.reset(); enqueues.reset(); dequeues.reset(); receivedCount.reset(); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); enqueues.setEnabled(enabled); dequeues.setEnabled(enabled); receivedCount.setEnabled(enabled); } public void setParent(NetworkBridgeStatistics parent) { if (parent != null) { enqueues.setParent(parent.enqueues); dequeues.setParent(parent.dequeues); receivedCount.setParent(parent.receivedCount); } else { enqueues.setParent(null); dequeues.setParent(null); receivedCount.setParent(null); } } } |
data class | Long method2 Repetitive code 3 Feature envy 4 Primitive obsession 5 Inappropriate intimate accessor 6 Inconsistent naming convention 7 Poor naming 8 Dead code 9 Data class | t | f | t | 0 | 14518 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/network/NetworkBridgeStatistics.java/#L26-L102 | 2 | 2453 | 14518 | minor | ||
| 519 | {"message": "YES, I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Targeting extends APINode { @SerializedName("adgroup_id") private String mAdgroupId = null; @SerializedName("age_max") private Long mAgeMax = null; @SerializedName("age_min") private Long mAgeMin = null; @SerializedName("alternate_auto_targeting_option") private String mAlternateAutoTargetingOption = null; @SerializedName("app_install_state") private String mAppInstallState = null; @SerializedName("audience_network_positions") private List mAudienceNetworkPositions = null; @SerializedName("behaviors") private List mBehaviors = null; @SerializedName("brand_safety_content_filter_levels") private List mBrandSafetyContentFilterLevels = null; @SerializedName("brand_safety_content_severity_levels") private List mBrandSafetyContentSeverityLevels = null; @SerializedName("catalog_based_targeting") private CatalogBasedTargeting mCatalogBasedTargeting = null; @SerializedName("cities") private List mCities = null; @SerializedName("college_years") private List mCollegeYears = null; @SerializedName("connections") private List mConnections = null; @SerializedName("contextual_targeting_categories") private List mContextualTargetingCategories = null; @SerializedName("countries") private List mCountries = null; @SerializedName("country") private List mCountry = null; @SerializedName("country_groups") private List mCountryGroups = null; @SerializedName("custom_audiences") private List mCustomAudiences = null; @SerializedName("device_platforms") private List mDevicePlatforms = null; @SerializedName("direct_install_devices") private Boolean mDirectInstallDevices = null; @SerializedName("dynamic_audience_ids") private List mDynamicAudienceIds = null; @SerializedName("education_majors") private List mEducationMajors = null; @SerializedName("education_schools") private List mEducationSchools = null; @SerializedName("education_statuses") private List mEducationStatuses = null; @SerializedName("effective_audience_network_positions") private List mEffectiveAudienceNetworkPositions = null; @SerializedName("effective_device_platforms") private List mEffectiveDevicePlatforms = null; @SerializedName("effective_facebook_positions") private List mEffectiveFacebookPositions = null; @SerializedName("effective_instagram_positions") private List mEffectiveInstagramPositions = null; @SerializedName("effective_messenger_positions") private List mEffectiveMessengerPositions = null; @SerializedName("effective_publisher_platforms") private List mEffectivePublisherPlatforms = null; @SerializedName("engagement_specs") private List mEngagementSpecs = null; @SerializedName("ethnic_affinity") private List mEthnicAffinity = null; @SerializedName("exclude_reached_since") private List mExcludeReachedSince = null; @SerializedName("excluded_connections") private List mExcludedConnections = null; @SerializedName("excluded_custom_audiences") private List mExcludedCustomAudiences = null; @SerializedName("excluded_dynamic_audience_ids") private List mExcludedDynamicAudienceIds = null; @SerializedName("excluded_engagement_specs") private List mExcludedEngagementSpecs = null; @SerializedName("excluded_geo_locations") private TargetingGeoLocation mExcludedGeoLocations = null; @SerializedName("excluded_mobile_device_model") private List mExcludedMobileDeviceModel = null; @SerializedName("excluded_product_audience_specs") private List mExcludedProductAudienceSpecs = null; @SerializedName("excluded_publisher_categories") private List mExcludedPublisherCategories = null; @SerializedName("excluded_publisher_list_ids") private List mExcludedPublisherListIds = null; @SerializedName("excluded_user_device") private List mExcludedUserDevice = null; @SerializedName("exclusions") private FlexibleTargeting mExclusions = null; @SerializedName("facebook_positions") private List mFacebookPositions = null; @SerializedName("family_statuses") private List mFamilyStatuses = null; @SerializedName("fb_deal_id") private String mFbDealId = null; @SerializedName("flexible_spec") private List mFlexibleSpec = null; @SerializedName("friends_of_connections") private List mFriendsOfConnections = null; @SerializedName("genders") private List mGenders = null; @SerializedName("generation") private List mGeneration = null; @SerializedName("geo_locations") private TargetingGeoLocation mGeoLocations = null; @SerializedName("home_ownership") private List mHomeOwnership = null; @SerializedName("home_type") private List mHomeType = null; @SerializedName("home_value") private List mHomeValue = null; @SerializedName("household_composition") private List mHouseholdComposition = null; @SerializedName("income") private List mIncome = null; @SerializedName("industries") private List mIndustries = null; @SerializedName("instagram_positions") private List mInstagramPositions = null; @SerializedName("instream_video_sponsorship_placements") private List mInstreamVideoSponsorshipPlacements = null; @SerializedName("interested_in") private List mInterestedIn = null; @SerializedName("interests") private List mInterests = null; @SerializedName("is_whatsapp_destination_ad") private Boolean mIsWhatsappDestinationAd = null; @SerializedName("keywords") private List mKeywords = null; @SerializedName("life_events") private List mLifeEvents = null; @SerializedName("locales") private List mLocales = null; @SerializedName("messenger_positions") private List mMessengerPositions = null; @SerializedName("moms") private List mMoms = null; @SerializedName("net_worth") private List mNetWorth = null; @SerializedName("office_type") private List mOfficeType = null; @SerializedName("place_page_set_ids") private List mPlacePageSetIds = null; @SerializedName("political_views") private List mPoliticalViews = null; @SerializedName("politics") private List mPolitics = null; @SerializedName("product_audience_specs") private List mProductAudienceSpecs = null; @SerializedName("prospecting_audience") private TargetingProspectingAudience mProspectingAudience = null; @SerializedName("publisher_platforms") private List mPublisherPlatforms = null; @SerializedName("publisher_visibility_categories") private List mPublisherVisibilityCategories = null; @SerializedName("radius") private String mRadius = null; @SerializedName("regions") private List mRegions = null; @SerializedName("relationship_statuses") private List mRelationshipStatuses = null; @SerializedName("site_category") private List mSiteCategory = null; @SerializedName("targeting_optimization") private String mTargetingOptimization = null; @SerializedName("user_adclusters") private List mUserAdclusters = null; @SerializedName("user_device") private List mUserDevice = null; @SerializedName("user_event") private List mUserEvent = null; @SerializedName("user_os") private List mUserOs = null; @SerializedName("wireless_carrier") private List mWirelessCarrier = null; @SerializedName("work_employers") private List mWorkEmployers = null; @SerializedName("work_positions") private List mWorkPositions = null; @SerializedName("zips") private List mZips = null; protected static Gson gson = null; public Targeting() { } public String getId() { return null; } public static Targeting loadJSON(String json, APIContext context, String header) { Targeting targeting = getGson().fromJson(json, Targeting.class); if (context.isDebug()) { JsonParser parser = new JsonParser(); JsonElement o1 = parser.parse(json); JsonElement o2 = parser.parse(targeting.toString()); if (o1.getAsJsonObject().get("__fb_trace_id__") != null) { o2.getAsJsonObject().add("__fb_trace_id__", o1.getAsJsonObject().get("__fb_trace_id__")); } if (!o1.equals(o2)) { context.log("[Warning] When parsing response, object is not consistent with JSON:"); context.log("[JSON]" + o1); context.log("[Object]" + o2); }; } targeting.context = context; targeting.rawValue = json; targeting.header = header; return targeting; } public static APINodeList parseResponse(String json, APIContext context, APIRequest request, String header) throws MalformedResponseException { APINodeList targetings = new APINodeList(request, json, header); JsonArray arr; JsonObject obj; JsonParser parser = new JsonParser(); Exception exception = null; try{ JsonElement result = parser.parse(json); if (result.isJsonArray()) { // First, check if it's a pure JSON Array arr = result.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; return targetings; } else if (result.isJsonObject()) { obj = result.getAsJsonObject(); if (obj.has("data")) { if (obj.has("paging")) { JsonObject paging = obj.get("paging").getAsJsonObject(); if (paging.has("cursors")) { JsonObject cursors = paging.get("cursors").getAsJsonObject(); String before = cursors.has("before") ? cursors.get("before").getAsString() : null; String after = cursors.has("after") ? cursors.get("after").getAsString() : null; targetings.setCursors(before, after); } String previous = paging.has("previous") ? paging.get("previous").getAsString() : null; String next = paging.has("next") ? paging.get("next").getAsString() : null; targetings.setPaging(previous, next); if (context.hasAppSecret()) { targetings.setAppSecret(context.getAppSecretProof()); } } if (obj.get("data").isJsonArray()) { // Second, check if it's a JSON array with "data" arr = obj.get("data").getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { targetings.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context, header)); }; } else if (obj.get("data").isJsonObject()) { // Third, check if it's a JSON object with "data" obj = obj.get("data").getAsJsonObject(); boolean isRedownload = false; for (String s : new String[]{"campaigns", "adsets", "ads"}) { if (obj.has(s)) { isRedownload = true; obj = obj.getAsJsonObject(s); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } break; } } if (!isRedownload) { targetings.add(loadJSON(obj.toString(), context, header)); } } return targetings; } else if (obj.has("images")) { // Fourth, check if it's a map of image objects obj = obj.get("images").getAsJsonObject(); for (Map.Entry entry : obj.entrySet()) { targetings.add(loadJSON(entry.getValue().toString(), context, header)); } return targetings; } else { // Fifth, check if it's an array of objects indexed by id boolean isIdIndexedArray = true; for (Map.Entry entry : obj.entrySet()) { String key = (String) entry.getKey(); if (key.equals("__fb_trace_id__")) { continue; } JsonElement value = (JsonElement) entry.getValue(); if ( value != null && value.isJsonObject() && value.getAsJsonObject().has("id") && value.getAsJsonObject().get("id") != null && value.getAsJsonObject().get("id").getAsString().equals(key) ) { targetings.add(loadJSON(value.toString(), context, header)); } else { isIdIndexedArray = false; break; } } if (isIdIndexedArray) { return targetings; } // Sixth, check if it's pure JsonObject targetings.clear(); targetings.add(loadJSON(json, context, header)); return targetings; } } } catch (Exception e) { exception = e; } throw new MalformedResponseException( "Invalid response string: " + json, exception ); } @Override public APIContext getContext() { return context; } @Override public void setContext(APIContext context) { this.context = context; } @Override public String toString() { return getGson().toJson(this); } public String getFieldAdgroupId() { return mAdgroupId; } public Targeting setFieldAdgroupId(String value) { this.mAdgroupId = value; return this; } public Long getFieldAgeMax() { return mAgeMax; } public Targeting setFieldAgeMax(Long value) { this.mAgeMax = value; return this; } public Long getFieldAgeMin() { return mAgeMin; } public Targeting setFieldAgeMin(Long value) { this.mAgeMin = value; return this; } public String getFieldAlternateAutoTargetingOption() { return mAlternateAutoTargetingOption; } public Targeting setFieldAlternateAutoTargetingOption(String value) { this.mAlternateAutoTargetingOption = value; return this; } public String getFieldAppInstallState() { return mAppInstallState; } public Targeting setFieldAppInstallState(String value) { this.mAppInstallState = value; return this; } public List getFieldAudienceNetworkPositions() { return mAudienceNetworkPositions; } public Targeting setFieldAudienceNetworkPositions(List value) { this.mAudienceNetworkPositions = value; return this; } public List getFieldBehaviors() { return mBehaviors; } public Targeting setFieldBehaviors(List value) { this.mBehaviors = value; return this; } public Targeting setFieldBehaviors(String value) { Type type = new TypeToken>(){}.getType(); this.mBehaviors = IDName.getGson().fromJson(value, type); return this; } public List getFieldBrandSafetyContentFilterLevels() { return mBrandSafetyContentFilterLevels; } public Targeting setFieldBrandSafetyContentFilterLevels(List value) { this.mBrandSafetyContentFilterLevels = value; return this; } public List getFieldBrandSafetyContentSeverityLevels() { return mBrandSafetyContentSeverityLevels; } public Targeting setFieldBrandSafetyContentSeverityLevels(List value) { this.mBrandSafetyContentSeverityLevels = value; return this; } public CatalogBasedTargeting getFieldCatalogBasedTargeting() { return mCatalogBasedTargeting; } public Targeting setFieldCatalogBasedTargeting(CatalogBasedTargeting value) { this.mCatalogBasedTargeting = value; return this; } public Targeting setFieldCatalogBasedTargeting(String value) { Type type = new TypeToken(){}.getType(); this.mCatalogBasedTargeting = CatalogBasedTargeting.getGson().fromJson(value, type); return this; } public List getFieldCities() { return mCities; } public Targeting setFieldCities(List value) { this.mCities = value; return this; } public Targeting setFieldCities(String value) { Type type = new TypeToken>(){}.getType(); this.mCities = IDName.getGson().fromJson(value, type); return this; } public List getFieldCollegeYears() { return mCollegeYears; } public Targeting setFieldCollegeYears(List value) { this.mCollegeYears = value; return this; } public List getFieldConnections() { return mConnections; } public Targeting setFieldConnections(List value) { this.mConnections = value; return this; } public Targeting setFieldConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldContextualTargetingCategories() { return mContextualTargetingCategories; } public Targeting setFieldContextualTargetingCategories(List value) { this.mContextualTargetingCategories = value; return this; } public Targeting setFieldContextualTargetingCategories(String value) { Type type = new TypeToken>(){}.getType(); this.mContextualTargetingCategories = IDName.getGson().fromJson(value, type); return this; } public List getFieldCountries() { return mCountries; } public Targeting setFieldCountries(List value) { this.mCountries = value; return this; } public List getFieldCountry() { return mCountry; } public Targeting setFieldCountry(List value) { this.mCountry = value; return this; } public List getFieldCountryGroups() { return mCountryGroups; } public Targeting setFieldCountryGroups(List value) { this.mCountryGroups = value; return this; } public List getFieldCustomAudiences() { return mCustomAudiences; } public Targeting setFieldCustomAudiences(List value) { this.mCustomAudiences = value; return this; } public Targeting setFieldCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mCustomAudiences = RawCustomAudience.getGson().fromJson(value, type); return this; } public List getFieldDevicePlatforms() { return mDevicePlatforms; } public Targeting setFieldDevicePlatforms(List value) { this.mDevicePlatforms = value; return this; } public Boolean getFieldDirectInstallDevices() { return mDirectInstallDevices; } public Targeting setFieldDirectInstallDevices(Boolean value) { this.mDirectInstallDevices = value; return this; } public List getFieldDynamicAudienceIds() { return mDynamicAudienceIds; } public Targeting setFieldDynamicAudienceIds(List value) { this.mDynamicAudienceIds = value; return this; } public List getFieldEducationMajors() { return mEducationMajors; } public Targeting setFieldEducationMajors(List value) { this.mEducationMajors = value; return this; } public Targeting setFieldEducationMajors(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationMajors = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationSchools() { return mEducationSchools; } public Targeting setFieldEducationSchools(List value) { this.mEducationSchools = value; return this; } public Targeting setFieldEducationSchools(String value) { Type type = new TypeToken>(){}.getType(); this.mEducationSchools = IDName.getGson().fromJson(value, type); return this; } public List getFieldEducationStatuses() { return mEducationStatuses; } public Targeting setFieldEducationStatuses(List value) { this.mEducationStatuses = value; return this; } public List getFieldEffectiveAudienceNetworkPositions() { return mEffectiveAudienceNetworkPositions; } public Targeting setFieldEffectiveAudienceNetworkPositions(List value) { this.mEffectiveAudienceNetworkPositions = value; return this; } public List getFieldEffectiveDevicePlatforms() { return mEffectiveDevicePlatforms; } public Targeting setFieldEffectiveDevicePlatforms(List value) { this.mEffectiveDevicePlatforms = value; return this; } public List getFieldEffectiveFacebookPositions() { return mEffectiveFacebookPositions; } public Targeting setFieldEffectiveFacebookPositions(List value) { this.mEffectiveFacebookPositions = value; return this; } public List getFieldEffectiveInstagramPositions() { return mEffectiveInstagramPositions; } public Targeting setFieldEffectiveInstagramPositions(List value) { this.mEffectiveInstagramPositions = value; return this; } public List getFieldEffectiveMessengerPositions() { return mEffectiveMessengerPositions; } public Targeting setFieldEffectiveMessengerPositions(List value) { this.mEffectiveMessengerPositions = value; return this; } public List getFieldEffectivePublisherPlatforms() { return mEffectivePublisherPlatforms; } public Targeting setFieldEffectivePublisherPlatforms(List value) { this.mEffectivePublisherPlatforms = value; return this; } public List getFieldEngagementSpecs() { return mEngagementSpecs; } public Targeting setFieldEngagementSpecs(List value) { this.mEngagementSpecs = value; return this; } public Targeting setFieldEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public List getFieldEthnicAffinity() { return mEthnicAffinity; } public Targeting setFieldEthnicAffinity(List value) { this.mEthnicAffinity = value; return this; } public Targeting setFieldEthnicAffinity(String value) { Type type = new TypeToken>(){}.getType(); this.mEthnicAffinity = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludeReachedSince() { return mExcludeReachedSince; } public Targeting setFieldExcludeReachedSince(List value) { this.mExcludeReachedSince = value; return this; } public List getFieldExcludedConnections() { return mExcludedConnections; } public Targeting setFieldExcludedConnections(List value) { this.mExcludedConnections = value; return this; } public Targeting setFieldExcludedConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedCustomAudiences() { return mExcludedCustomAudiences; } public Targeting setFieldExcludedCustomAudiences(List value) { this.mExcludedCustomAudiences = value; return this; } public Targeting setFieldExcludedCustomAudiences(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedCustomAudiences = IDName.getGson().fromJson(value, type); return this; } public List getFieldExcludedDynamicAudienceIds() { return mExcludedDynamicAudienceIds; } public Targeting setFieldExcludedDynamicAudienceIds(List value) { this.mExcludedDynamicAudienceIds = value; return this; } public List getFieldExcludedEngagementSpecs() { return mExcludedEngagementSpecs; } public Targeting setFieldExcludedEngagementSpecs(List value) { this.mExcludedEngagementSpecs = value; return this; } public Targeting setFieldExcludedEngagementSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedEngagementSpecs = TargetingDynamicRule.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldExcludedGeoLocations() { return mExcludedGeoLocations; } public Targeting setFieldExcludedGeoLocations(TargetingGeoLocation value) { this.mExcludedGeoLocations = value; return this; } public Targeting setFieldExcludedGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mExcludedGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldExcludedMobileDeviceModel() { return mExcludedMobileDeviceModel; } public Targeting setFieldExcludedMobileDeviceModel(List value) { this.mExcludedMobileDeviceModel = value; return this; } public List getFieldExcludedProductAudienceSpecs() { return mExcludedProductAudienceSpecs; } public Targeting setFieldExcludedProductAudienceSpecs(List value) { this.mExcludedProductAudienceSpecs = value; return this; } public Targeting setFieldExcludedProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mExcludedProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public List getFieldExcludedPublisherCategories() { return mExcludedPublisherCategories; } public Targeting setFieldExcludedPublisherCategories(List value) { this.mExcludedPublisherCategories = value; return this; } public List getFieldExcludedPublisherListIds() { return mExcludedPublisherListIds; } public Targeting setFieldExcludedPublisherListIds(List value) { this.mExcludedPublisherListIds = value; return this; } public List getFieldExcludedUserDevice() { return mExcludedUserDevice; } public Targeting setFieldExcludedUserDevice(List value) { this.mExcludedUserDevice = value; return this; } public FlexibleTargeting getFieldExclusions() { return mExclusions; } public Targeting setFieldExclusions(FlexibleTargeting value) { this.mExclusions = value; return this; } public Targeting setFieldExclusions(String value) { Type type = new TypeToken(){}.getType(); this.mExclusions = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFacebookPositions() { return mFacebookPositions; } public Targeting setFieldFacebookPositions(List value) { this.mFacebookPositions = value; return this; } public List getFieldFamilyStatuses() { return mFamilyStatuses; } public Targeting setFieldFamilyStatuses(List value) { this.mFamilyStatuses = value; return this; } public Targeting setFieldFamilyStatuses(String value) { Type type = new TypeToken>(){}.getType(); this.mFamilyStatuses = IDName.getGson().fromJson(value, type); return this; } public String getFieldFbDealId() { return mFbDealId; } public Targeting setFieldFbDealId(String value) { this.mFbDealId = value; return this; } public List getFieldFlexibleSpec() { return mFlexibleSpec; } public Targeting setFieldFlexibleSpec(List value) { this.mFlexibleSpec = value; return this; } public Targeting setFieldFlexibleSpec(String value) { Type type = new TypeToken>(){}.getType(); this.mFlexibleSpec = FlexibleTargeting.getGson().fromJson(value, type); return this; } public List getFieldFriendsOfConnections() { return mFriendsOfConnections; } public Targeting setFieldFriendsOfConnections(List value) { this.mFriendsOfConnections = value; return this; } public Targeting setFieldFriendsOfConnections(String value) { Type type = new TypeToken>(){}.getType(); this.mFriendsOfConnections = IDName.getGson().fromJson(value, type); return this; } public List getFieldGenders() { return mGenders; } public Targeting setFieldGenders(List value) { this.mGenders = value; return this; } public List getFieldGeneration() { return mGeneration; } public Targeting setFieldGeneration(List value) { this.mGeneration = value; return this; } public Targeting setFieldGeneration(String value) { Type type = new TypeToken>(){}.getType(); this.mGeneration = IDName.getGson().fromJson(value, type); return this; } public TargetingGeoLocation getFieldGeoLocations() { return mGeoLocations; } public Targeting setFieldGeoLocations(TargetingGeoLocation value) { this.mGeoLocations = value; return this; } public Targeting setFieldGeoLocations(String value) { Type type = new TypeToken(){}.getType(); this.mGeoLocations = TargetingGeoLocation.getGson().fromJson(value, type); return this; } public List getFieldHomeOwnership() { return mHomeOwnership; } public Targeting setFieldHomeOwnership(List value) { this.mHomeOwnership = value; return this; } public Targeting setFieldHomeOwnership(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeOwnership = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeType() { return mHomeType; } public Targeting setFieldHomeType(List value) { this.mHomeType = value; return this; } public Targeting setFieldHomeType(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldHomeValue() { return mHomeValue; } public Targeting setFieldHomeValue(List value) { this.mHomeValue = value; return this; } public Targeting setFieldHomeValue(String value) { Type type = new TypeToken>(){}.getType(); this.mHomeValue = IDName.getGson().fromJson(value, type); return this; } public List getFieldHouseholdComposition() { return mHouseholdComposition; } public Targeting setFieldHouseholdComposition(List value) { this.mHouseholdComposition = value; return this; } public Targeting setFieldHouseholdComposition(String value) { Type type = new TypeToken>(){}.getType(); this.mHouseholdComposition = IDName.getGson().fromJson(value, type); return this; } public List getFieldIncome() { return mIncome; } public Targeting setFieldIncome(List value) { this.mIncome = value; return this; } public Targeting setFieldIncome(String value) { Type type = new TypeToken>(){}.getType(); this.mIncome = IDName.getGson().fromJson(value, type); return this; } public List getFieldIndustries() { return mIndustries; } public Targeting setFieldIndustries(List value) { this.mIndustries = value; return this; } public Targeting setFieldIndustries(String value) { Type type = new TypeToken>(){}.getType(); this.mIndustries = IDName.getGson().fromJson(value, type); return this; } public List getFieldInstagramPositions() { return mInstagramPositions; } public Targeting setFieldInstagramPositions(List value) { this.mInstagramPositions = value; return this; } public List getFieldInstreamVideoSponsorshipPlacements() { return mInstreamVideoSponsorshipPlacements; } public Targeting setFieldInstreamVideoSponsorshipPlacements(List value) { this.mInstreamVideoSponsorshipPlacements = value; return this; } public List getFieldInterestedIn() { return mInterestedIn; } public Targeting setFieldInterestedIn(List value) { this.mInterestedIn = value; return this; } public List getFieldInterests() { return mInterests; } public Targeting setFieldInterests(List value) { this.mInterests = value; return this; } public Targeting setFieldInterests(String value) { Type type = new TypeToken>(){}.getType(); this.mInterests = IDName.getGson().fromJson(value, type); return this; } public Boolean getFieldIsWhatsappDestinationAd() { return mIsWhatsappDestinationAd; } public Targeting setFieldIsWhatsappDestinationAd(Boolean value) { this.mIsWhatsappDestinationAd = value; return this; } public List getFieldKeywords() { return mKeywords; } public Targeting setFieldKeywords(List value) { this.mKeywords = value; return this; } public List getFieldLifeEvents() { return mLifeEvents; } public Targeting setFieldLifeEvents(List value) { this.mLifeEvents = value; return this; } public Targeting setFieldLifeEvents(String value) { Type type = new TypeToken>(){}.getType(); this.mLifeEvents = IDName.getGson().fromJson(value, type); return this; } public List getFieldLocales() { return mLocales; } public Targeting setFieldLocales(List value) { this.mLocales = value; return this; } public List getFieldMessengerPositions() { return mMessengerPositions; } public Targeting setFieldMessengerPositions(List value) { this.mMessengerPositions = value; return this; } public List getFieldMoms() { return mMoms; } public Targeting setFieldMoms(List value) { this.mMoms = value; return this; } public Targeting setFieldMoms(String value) { Type type = new TypeToken>(){}.getType(); this.mMoms = IDName.getGson().fromJson(value, type); return this; } public List getFieldNetWorth() { return mNetWorth; } public Targeting setFieldNetWorth(List value) { this.mNetWorth = value; return this; } public Targeting setFieldNetWorth(String value) { Type type = new TypeToken>(){}.getType(); this.mNetWorth = IDName.getGson().fromJson(value, type); return this; } public List getFieldOfficeType() { return mOfficeType; } public Targeting setFieldOfficeType(List value) { this.mOfficeType = value; return this; } public Targeting setFieldOfficeType(String value) { Type type = new TypeToken>(){}.getType(); this.mOfficeType = IDName.getGson().fromJson(value, type); return this; } public List getFieldPlacePageSetIds() { return mPlacePageSetIds; } public Targeting setFieldPlacePageSetIds(List value) { this.mPlacePageSetIds = value; return this; } public List getFieldPoliticalViews() { return mPoliticalViews; } public Targeting setFieldPoliticalViews(List value) { this.mPoliticalViews = value; return this; } public List getFieldPolitics() { return mPolitics; } public Targeting setFieldPolitics(List value) { this.mPolitics = value; return this; } public Targeting setFieldPolitics(String value) { Type type = new TypeToken>(){}.getType(); this.mPolitics = IDName.getGson().fromJson(value, type); return this; } public List getFieldProductAudienceSpecs() { return mProductAudienceSpecs; } public Targeting setFieldProductAudienceSpecs(List value) { this.mProductAudienceSpecs = value; return this; } public Targeting setFieldProductAudienceSpecs(String value) { Type type = new TypeToken>(){}.getType(); this.mProductAudienceSpecs = TargetingProductAudienceSpec.getGson().fromJson(value, type); return this; } public TargetingProspectingAudience getFieldProspectingAudience() { return mProspectingAudience; } public Targeting setFieldProspectingAudience(TargetingProspectingAudience value) { this.mProspectingAudience = value; return this; } public Targeting setFieldProspectingAudience(String value) { Type type = new TypeToken(){}.getType(); this.mProspectingAudience = TargetingProspectingAudience.getGson().fromJson(value, type); return this; } public List getFieldPublisherPlatforms() { return mPublisherPlatforms; } public Targeting setFieldPublisherPlatforms(List value) { this.mPublisherPlatforms = value; return this; } public List getFieldPublisherVisibilityCategories() { return mPublisherVisibilityCategories; } public Targeting setFieldPublisherVisibilityCategories(List value) { this.mPublisherVisibilityCategories = value; return this; } public String getFieldRadius() { return mRadius; } public Targeting setFieldRadius(String value) { this.mRadius = value; return this; } public List getFieldRegions() { return mRegions; } public Targeting setFieldRegions(List value) { this.mRegions = value; return this; } public Targeting setFieldRegions(String value) { Type type = new TypeToken>(){}.getType(); this.mRegions = IDName.getGson().fromJson(value, type); return this; } public List getFieldRelationshipStatuses() { return mRelationshipStatuses; } public Targeting setFieldRelationshipStatuses(List value) { this.mRelationshipStatuses = value; return this; } public List getFieldSiteCategory() { return mSiteCategory; } public Targeting setFieldSiteCategory(List value) { this.mSiteCategory = value; return this; } public String getFieldTargetingOptimization() { return mTargetingOptimization; } public Targeting setFieldTargetingOptimization(String value) { this.mTargetingOptimization = value; return this; } public List getFieldUserAdclusters() { return mUserAdclusters; } public Targeting setFieldUserAdclusters(List value) { this.mUserAdclusters = value; return this; } public Targeting setFieldUserAdclusters(String value) { Type type = new TypeToken>(){}.getType(); this.mUserAdclusters = IDName.getGson().fromJson(value, type); return this; } public List getFieldUserDevice() { return mUserDevice; } public Targeting setFieldUserDevice(List value) { this.mUserDevice = value; return this; } public List getFieldUserEvent() { return mUserEvent; } public Targeting setFieldUserEvent(List value) { this.mUserEvent = value; return this; } public List getFieldUserOs() { return mUserOs; } public Targeting setFieldUserOs(List value) { this.mUserOs = value; return this; } public List getFieldWirelessCarrier() { return mWirelessCarrier; } public Targeting setFieldWirelessCarrier(List value) { this.mWirelessCarrier = value; return this; } public List getFieldWorkEmployers() { return mWorkEmployers; } public Targeting setFieldWorkEmployers(List value) { this.mWorkEmployers = value; return this; } public Targeting setFieldWorkEmployers(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkEmployers = IDName.getGson().fromJson(value, type); return this; } public List getFieldWorkPositions() { return mWorkPositions; } public Targeting setFieldWorkPositions(List value) { this.mWorkPositions = value; return this; } public Targeting setFieldWorkPositions(String value) { Type type = new TypeToken>(){}.getType(); this.mWorkPositions = IDName.getGson().fromJson(value, type); return this; } public List getFieldZips() { return mZips; } public Targeting setFieldZips(List value) { this.mZips = value; return this; } public static enum EnumDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } public static enum EnumEffectiveDevicePlatforms { @SerializedName("connected_tv") VALUE_CONNECTED_TV("connected_tv"), @SerializedName("desktop") VALUE_DESKTOP("desktop"), @SerializedName("mobile") VALUE_MOBILE("mobile"), NULL(null); private String value; private EnumEffectiveDevicePlatforms(String value) { this.value = value; } @Override public String toString() { return value; } } synchronized /*package*/ static Gson getGson() { if (gson != null) { return gson; } else { gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .excludeFieldsWithModifiers(Modifier.PROTECTED) .disableHtmlEscaping() .create(); } return gson; } public Targeting copyFrom(Targeting instance) { this.mAdgroupId = instance.mAdgroupId; this.mAgeMax = instance.mAgeMax; this.mAgeMin = instance.mAgeMin; this.mAlternateAutoTargetingOption = instance.mAlternateAutoTargetingOption; this.mAppInstallState = instance.mAppInstallState; this.mAudienceNetworkPositions = instance.mAudienceNetworkPositions; this.mBehaviors = instance.mBehaviors; this.mBrandSafetyContentFilterLevels = instance.mBrandSafetyContentFilterLevels; this.mBrandSafetyContentSeverityLevels = instance.mBrandSafetyContentSeverityLevels; this.mCatalogBasedTargeting = instance.mCatalogBasedTargeting; this.mCities = instance.mCities; this.mCollegeYears = instance.mCollegeYears; this.mConnections = instance.mConnections; this.mContextualTargetingCategories = instance.mContextualTargetingCategories; this.mCountries = instance.mCountries; this.mCountry = instance.mCountry; this.mCountryGroups = instance.mCountryGroups; this.mCustomAudiences = instance.mCustomAudiences; this.mDevicePlatforms = instance.mDevicePlatforms; this.mDirectInstallDevices = instance.mDirectInstallDevices; this.mDynamicAudienceIds = instance.mDynamicAudienceIds; this.mEducationMajors = instance.mEducationMajors; this.mEducationSchools = instance.mEducationSchools; this.mEducationStatuses = instance.mEducationStatuses; this.mEffectiveAudienceNetworkPositions = instance.mEffectiveAudienceNetworkPositions; this.mEffectiveDevicePlatforms = instance.mEffectiveDevicePlatforms; this.mEffectiveFacebookPositions = instance.mEffectiveFacebookPositions; this.mEffectiveInstagramPositions = instance.mEffectiveInstagramPositions; this.mEffectiveMessengerPositions = instance.mEffectiveMessengerPositions; this.mEffectivePublisherPlatforms = instance.mEffectivePublisherPlatforms; this.mEngagementSpecs = instance.mEngagementSpecs; this.mEthnicAffinity = instance.mEthnicAffinity; this.mExcludeReachedSince = instance.mExcludeReachedSince; this.mExcludedConnections = instance.mExcludedConnections; this.mExcludedCustomAudiences = instance.mExcludedCustomAudiences; this.mExcludedDynamicAudienceIds = instance.mExcludedDynamicAudienceIds; this.mExcludedEngagementSpecs = instance.mExcludedEngagementSpecs; this.mExcludedGeoLocations = instance.mExcludedGeoLocations; this.mExcludedMobileDeviceModel = instance.mExcludedMobileDeviceModel; this.mExcludedProductAudienceSpecs = instance.mExcludedProductAudienceSpecs; this.mExcludedPublisherCategories = instance.mExcludedPublisherCategories; this.mExcludedPublisherListIds = instance.mExcludedPublisherListIds; this.mExcludedUserDevice = instance.mExcludedUserDevice; this.mExclusions = instance.mExclusions; this.mFacebookPositions = instance.mFacebookPositions; this.mFamilyStatuses = instance.mFamilyStatuses; this.mFbDealId = instance.mFbDealId; this.mFlexibleSpec = instance.mFlexibleSpec; this.mFriendsOfConnections = instance.mFriendsOfConnections; this.mGenders = instance.mGenders; this.mGeneration = instance.mGeneration; this.mGeoLocations = instance.mGeoLocations; this.mHomeOwnership = instance.mHomeOwnership; this.mHomeType = instance.mHomeType; this.mHomeValue = instance.mHomeValue; this.mHouseholdComposition = instance.mHouseholdComposition; this.mIncome = instance.mIncome; this.mIndustries = instance.mIndustries; this.mInstagramPositions = instance.mInstagramPositions; this.mInstreamVideoSponsorshipPlacements = instance.mInstreamVideoSponsorshipPlacements; this.mInterestedIn = instance.mInterestedIn; this.mInterests = instance.mInterests; this.mIsWhatsappDestinationAd = instance.mIsWhatsappDestinationAd; this.mKeywords = instance.mKeywords; this.mLifeEvents = instance.mLifeEvents; this.mLocales = instance.mLocales; this.mMessengerPositions = instance.mMessengerPositions; this.mMoms = instance.mMoms; this.mNetWorth = instance.mNetWorth; this.mOfficeType = instance.mOfficeType; this.mPlacePageSetIds = instance.mPlacePageSetIds; this.mPoliticalViews = instance.mPoliticalViews; this.mPolitics = instance.mPolitics; this.mProductAudienceSpecs = instance.mProductAudienceSpecs; this.mProspectingAudience = instance.mProspectingAudience; this.mPublisherPlatforms = instance.mPublisherPlatforms; this.mPublisherVisibilityCategories = instance.mPublisherVisibilityCategories; this.mRadius = instance.mRadius; this.mRegions = instance.mRegions; this.mRelationshipStatuses = instance.mRelationshipStatuses; this.mSiteCategory = instance.mSiteCategory; this.mTargetingOptimization = instance.mTargetingOptimization; this.mUserAdclusters = instance.mUserAdclusters; this.mUserDevice = instance.mUserDevice; this.mUserEvent = instance.mUserEvent; this.mUserOs = instance.mUserOs; this.mWirelessCarrier = instance.mWirelessCarrier; this.mWorkEmployers = instance.mWorkEmployers; this.mWorkPositions = instance.mWorkPositions; this.mZips = instance.mZips; this.context = instance.context; this.rawValue = instance.rawValue; return this; } public static APIRequest.ResponseParser getParser() { return new APIRequest.ResponseParser() { public APINodeList parseResponse(String response, APIContext context, APIRequest request, String header) throws MalformedResponseException { return Targeting.parseResponse(response, context, request, header); } }; } } |
data class | data class | t | t | t | 0 | 5404 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/Targeting.java/#L57-L1555 | 1 | 519 | 5404 | critical | ||
| 1931 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method | t | t | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1931 | 12454 | major | ||
| 1646 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Large class 5. Indecent exposure (due to multiple public variables) 6. Combinatorial explosion (due to nested loops) 7. Lazy class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
feature envy | Long method2 Feature envy3 Duplicated code4 Large class5 Indecent exposure (due to multiple public variables)6 Combinatorial explosion (due to nested loops)7 Lazy class | t | f | t | 0 | 11562 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 2 | 1646 | 11562 | minor | ||
| 993 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 2 | 993 | 9070 | minor | ||
| 1297 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | data class | t | t | t | 0 | 10637 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 1 | 1297 | 10637 | major | ||
| 1495 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11124 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1495 | 11124 | major | |
| 1015 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class KafkaTestServer { public static final int CACHE_TTL_MS = 1; private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestServer.class); private int kafkaPort = -1; private TestingServer zkServer; private KafkaServerStartable kafkaServer = null; private File sentrySitePath = null; public KafkaTestServer(File sentrySitePath) throws Exception { this.sentrySitePath = sentrySitePath; createZkServer(); this.kafkaPort = TestUtils.getFreePort(); createKafkaServer(); } public void start() throws Exception { kafkaServer.startup(); LOGGER.info("Started Kafka broker."); } public void shutdown() { if (kafkaServer != null) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); LOGGER.info("Stopped Kafka server."); } if (zkServer != null) { try { zkServer.stop(); LOGGER.info("Stopped ZK server."); } catch (IOException e) { LOGGER.error("Failed to shutdown ZK server.", e); } } } private Path getTempDirectory() { Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory("kafka-sentry-"); } catch (IOException e) { LOGGER.error("Failed to create temp dir for Kafka's log dir."); throw new RuntimeException(e); } return tempDirectory; } private void setupKafkaProps(Properties props) throws UnknownHostException { props.put("listeners", "SSL://" + InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort); props.put("log.dir", getTempDirectory().toAbsolutePath().toString()); props.put("zookeeper.connect", zkServer.getConnectString()); props.put("replica.socket.timeout.ms", "1500"); props.put("controller.socket.timeout.ms", "1500"); props.put("controlled.shutdown.enable", true); props.put("delete.topic.enable", false); props.put("controlled.shutdown.retry.backoff.ms", "100"); props.put("port", kafkaPort); props.put("offsets.topic.replication.factor", "1"); props.put("authorizer.class.name", "org.apache.sentry.kafka.authorizer.SentryKafkaAuthorizer"); props.put("sentry.kafka.site.url", "file://" + sentrySitePath.getAbsolutePath()); props.put("allow.everyone.if.no.acl.found", "true"); props.put("ssl.keystore.location", KafkaTestServer.class.getResource("/test.keystore.jks").getPath()); props.put("ssl.keystore.password", "test-ks-passwd"); props.put("ssl.key.password", "test-key-passwd"); props.put("ssl.truststore.location", KafkaTestServer.class.getResource("/test.truststore.jks").getPath()); props.put("ssl.truststore.password", "test-ts-passwd"); props.put("security.inter.broker.protocol", "SSL"); props.put("ssl.client.auth", "required"); props.put(KafkaAuthConf.KAFKA_SUPER_USERS, "User:CN=superuser;User:CN=superuser1; User:CN=Superuser2 "); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_ENABLE_NAME, "true"); props.put(KafkaAuthConf.SENTRY_KAFKA_CACHING_TTL_MS_NAME, String.valueOf(CACHE_TTL_MS)); } private void createKafkaServer() throws UnknownHostException { Properties props = new Properties(); setupKafkaProps(props); kafkaServer = KafkaServerStartable.fromProps(props); } private void createZkServer() throws Exception { try { zkServer = new TestingServer(); } catch (Exception e) { LOGGER.error("Failed to create testing zookeeper server."); throw new RuntimeException(e); } } public String getBootstrapServers() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress() + ":" + kafkaPort; } } |
blob | long method, blob, data class | t | t | t | long method, data class | 0 | 9297 | https://github.com/apache/sentry/blob/f859446b65bbc274bc4899464892151eec8217c6/sentry-tests/sentry-tests-kafka/src/main/java/org/apache/sentry/tests/e2e/kafka/KafkaTestServer.java/#L35-L129 | 1 | 1015 | 9297 | minor | |
| 1959 | {"message": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | 1 Long Method | t | f | t | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 1959 | 12573 | minor | ||
| 2055 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 2055 | 12939 | major | ||
| 1446 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10983 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 2 | 1446 | 10983 | major | ||
| 2574 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | long method, blob | t | t | t | blob | 0 | 14912 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 1 | 2574 | 14912 | minor | |
| 1009 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9269 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 1009 | 9269 | major | ||
| 2148 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T get(Duration duration) throws InterruptedException, ExecutionException, TimeoutException { long start = System.currentTimeMillis(); Long end = duration==null ? null : start + duration.toMillisecondsRoundingUp(); while (end==null || end > System.currentTimeMillis()) { if (cancelled) throw new CancellationException(); if (internalFuture == null) { synchronized (this) { long remaining = end - System.currentTimeMillis(); if (internalFuture==null && remaining>0) wait(remaining); } } if (internalFuture != null) break; } Long remaining = end==null ? null : end - System.currentTimeMillis(); if (isDone()) { return internalFuture.get(1, TimeUnit.MILLISECONDS); } else if (remaining == null) { return internalFuture.get(); } else if (remaining > 0) { return internalFuture.get(remaining, TimeUnit.MILLISECONDS); } else { throw new TimeoutException(); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 13280 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/task/BasicTask.java/#L437-L462 | 2 | 2148 | 13280 | minor | |
| 3714 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExistingEnumElements extends AbstractEnumRuleElementFinder { private final EnumRule rule = (EnumRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.enumrules.EnumRulesTestLanguage.ExistingEnum"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final EnumLiteralDeclaration cSameNameEnumLiteralDeclaration_0 = (EnumLiteralDeclaration)cAlternatives.eContents().get(0); private final Keyword cSameNameSameNameKeyword_0_0 = (Keyword)cSameNameEnumLiteralDeclaration_0.eContents().get(0); private final EnumLiteralDeclaration cOverriddenLiteralEnumLiteralDeclaration_1 = (EnumLiteralDeclaration)cAlternatives.eContents().get(1); private final Keyword cOverriddenLiteralOverriddenKeyword_1_0 = (Keyword)cOverriddenLiteralEnumLiteralDeclaration_1.eContents().get(0); private final EnumLiteralDeclaration cDifferentNameEnumLiteralDeclaration_2 = (EnumLiteralDeclaration)cAlternatives.eContents().get(2); private final Keyword cDifferentNameDifferentLiteralKeyword_2_0 = (Keyword)cDifferentNameEnumLiteralDeclaration_2.eContents().get(0); //enum ExistingEnum: // SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral"; public EnumRule getRule() { return rule; } //SameName | OverriddenLiteral="overridden" | DifferentName="DifferentLiteral" public Alternatives getAlternatives() { return cAlternatives; } //SameName public EnumLiteralDeclaration getSameNameEnumLiteralDeclaration_0() { return cSameNameEnumLiteralDeclaration_0; } //"SameName" public Keyword getSameNameSameNameKeyword_0_0() { return cSameNameSameNameKeyword_0_0; } //OverriddenLiteral="overridden" public EnumLiteralDeclaration getOverriddenLiteralEnumLiteralDeclaration_1() { return cOverriddenLiteralEnumLiteralDeclaration_1; } //"overridden" public Keyword getOverriddenLiteralOverriddenKeyword_1_0() { return cOverriddenLiteralOverriddenKeyword_1_0; } //DifferentName="DifferentLiteral" public EnumLiteralDeclaration getDifferentNameEnumLiteralDeclaration_2() { return cDifferentNameEnumLiteralDeclaration_2; } //"DifferentLiteral" public Keyword getDifferentNameDifferentLiteralKeyword_2_0() { return cDifferentNameDifferentLiteralKeyword_2_0; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 8980 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.extras.tests/src-gen/org/eclipse/xtext/enumrules/services/EnumRulesTestLanguageGrammarAccess.java/#L88-L122 | 1 | 3714 | 8980 | major | |
| 2533 | { "output": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14745 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 2533 | 14745 | minor | |
| 3902 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | long method | t | t | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 1 | 3902 | 10217 | minor | ||
| 1344 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10746 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1344 | 10746 | major | |
| 1947 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | 1. long method | t | t | f | long method | 0 | 12523 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 1947 | 12523 | major | |
| 1001 | {"message": "YES I found bad smells", "badSmells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static final class Reference { private final Tree tree; private final PropertyState property; private Reference(Tree tree, String propertyName) { this.tree = tree; this.property = tree.getProperty(propertyName); } private boolean isMultiple() { return property.isArray(); } private void setProperty(String newValue) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValue, property.getType().tag()); tree.setProperty(prop); } private void setProperty(Iterable newValues) { PropertyState prop = PropertyStates.createProperty(property.getName(), newValues, property.getType()); tree.setProperty(prop); } } |
data class | blob, data class | t | t | f | blob | data class | 0 | 9189 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java/#L548-L571 | 1 | 1001 | 9189 | major |
| 1479 | { "response": "YES I found bad smells", "the bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlTransient public abstract class PendingActionNotificationResponse extends ImmutableObject implements ResponseData { /** The inner name type that contains a name and the result boolean. */ @Embed static class NameOrId extends ImmutableObject { @XmlValue String value; @XmlAttribute(name = "paResult") boolean actionResult; } @XmlTransient NameOrId nameOrId; @XmlElement(name = "paTRID") Trid trid; @XmlElement(name = "paDate") DateTime processedDate; public String getNameAsString() { return nameOrId.value; } @VisibleForTesting public Trid getTrid() { return trid; } @VisibleForTesting public boolean getActionResult() { return nameOrId.actionResult; } protected static T init( T response, String nameOrId, boolean actionResult, Trid trid, DateTime processedDate) { response.nameOrId = new NameOrId(); response.nameOrId.value = nameOrId; response.nameOrId.actionResult = actionResult; response.trid = trid; response.processedDate = processedDate; return response; } /** An adapter to output the XML in response to resolving a pending command on a domain. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0") public static class DomainPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static DomainPendingActionNotificationResponse create( String fullyQualifiedDomainName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new DomainPendingActionNotificationResponse(), fullyQualifiedDomainName, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a contact. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:contact-1.0") @XmlType( propOrder = {"id", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:contact-1.0") public static class ContactPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getId() { return nameOrId; } public static ContactPendingActionNotificationResponse create( String contactId, boolean actionResult, Trid trid, DateTime processedDate) { return init( new ContactPendingActionNotificationResponse(), contactId, actionResult, trid, processedDate); } } /** An adapter to output the XML in response to resolving a pending command on a host. */ @Embed @XmlRootElement(name = "panData", namespace = "urn:ietf:params:xml:ns:domain-1.0") @XmlType( propOrder = {"name", "trid", "processedDate"}, namespace = "urn:ietf:params:xml:ns:domain-1.0" ) public static class HostPendingActionNotificationResponse extends PendingActionNotificationResponse { @XmlElement NameOrId getName() { return nameOrId; } public static HostPendingActionNotificationResponse create( String fullyQualifiedHostName, boolean actionResult, Trid trid, DateTime processedDate) { return init( new HostPendingActionNotificationResponse(), fullyQualifiedHostName, actionResult, trid, processedDate); } } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 11069 | https://github.com/google/nomulus/blob/2481704d00f10f6b5675dd26f9effaad434ddbea/java/google/registry/model/poll/PendingActionNotificationResponse.java/#L31-L153 | 1 | 1479 | 11069 | minor | |
| 1561 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long Method | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 1561 | 11308 | major | ||
| 2300 | {"message": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 14030 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 2300 | 14030 | major | ||
| 1445 | {"result": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
blob | blob, data class | t | t | t | data class | 0 | 10981 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 1445 | 10981 | major | |
| 885 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Repeated code 4. Data clump 5. Feature envy 6. Assert statements 7. Null checks 8. Incomplete error handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | Long method2 Magic numbers3 Repeated code4 Data clump5 Feature envy6 Assert statements7 Null checks8 Incomplete error handling | t | f | t | 0 | 8053 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 2 | 885 | 8053 | minor | ||
| 1390 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 1 | 1390 | 10841 | minor | |
| 2750 | YES I found bad smells 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 818 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 2 | 2750 | 818 | minor | ||
| 2131 | YES I found bad smells the bad smells are: 1. Duplicate code (creating multiple nodes) 2. Long method (contains multiple operations) 3. Feature envy (NodeManager.add method being used frequently) 4. Primitive obsession (defining variable types as double and integer instead of creating custom objects) 5. Catch and hide exception (no proper handling of the exception) 6. Lack of readability and organization, making it difficult to understand the flow of the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | Duplicate code (creating multiple nodes)2 Long method (contains multiple operations)3 Feature envy (NodeManageradd method being used frequently)4 Primitive obsession (defining variable types as double and integer instead of creating custom objects)5 Catch and hide exception (no proper handling of the exception)6 Lack of readability and organization, making it difficult to understand the flow of the code | t | f | t | making it difficult to understand the flow of the code. | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 2131 | 13232 | minor | |
| 1420 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long Method | t | f | t | 0 | 10928 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 1420 | 10928 | minor | ||
| 2684 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15270 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 2684 | 15270 | minor | ||
| 1681 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11679 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 1681 | 11679 | minor | ||
| 445 | YES I found bad smells. The bad smells are: 1. Long method 2. Redundant code 3. Code duplication 4. Complex control flow 5. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void rule__Action__OperatorAssignment_2_2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXtextGrammarTestLanguage.g:6076:1: ( ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) ) // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) { // InternalXtextGrammarTestLanguage.g:6077:2: ( ( rule__Action__OperatorAlternatives_2_2_0 ) ) // InternalXtextGrammarTestLanguage.g:6078:3: ( rule__Action__OperatorAlternatives_2_2_0 ) { before(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); // InternalXtextGrammarTestLanguage.g:6079:3: ( rule__Action__OperatorAlternatives_2_2_0 ) // InternalXtextGrammarTestLanguage.g:6079:4: rule__Action__OperatorAlternatives_2_2_0 { pushFollow(FOLLOW_2); rule__Action__OperatorAlternatives_2_2_0(); state._fsp--; } after(grammarAccess.getActionAccess().getOperatorAlternatives_2_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } |
long method | Long method 2 Redundant code 3 Code duplication 4 Complex control flow 5 Inconsistent naming conventions | t | f | t | 0 | 4346 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.testlanguages.ide/src-gen/org/eclipse/xtext/testlanguages/xtextgrammar/ide/contentassist/antlr/internal/InternalXtextGrammarTestLanguageParser.java/#L18472-L18513 | 2 | 445 | 4346 | minor | ||
| 941 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void setContentLength(final int length) { setIntHeader("Content-Length", length); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8463 | https://github.com/apache/wicket/blob/c2d344219ef8046508ca40653c9de485b3cbd4c4/wicket-core/src/main/java/org/apache/wicket/protocol/http/mock/MockHttpServletResponse.java/#L613-L617 | 2 | 941 | 8463 | minor | ||
| 78 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | data class | t | t | t | 0 | 1160 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 78 | 1160 | minor | ||
| 568 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 5726 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 568 | 5726 | minor | ||
| 971 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 2 | 971 | 8713 | major | |
| 2592 | ### YES I found bad smells 1. Long method 2. Feature envy 3. Primitive obsession 4. Data class 5. Inappropriate use of comments 6. Inconsistent formatting and naming conventions 7. Duplicated code 8. Inefficient data serialization handling 9. Inconsistent use of flags and boolean variables 10. Lack of proper exception handling 11. Unused and unnecessary methods 12. Inappropriate use of transient keyword. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class PutAllEntryData { final Object key; private Object value; private final Object oldValue; private final Operation op; private EventID eventID; transient EntryEventImpl event; private Integer bucketId = Integer.valueOf(-1); protected transient boolean callbacksInvoked = false; public FilterRoutingInfo filterRouting; // One flags byte for all booleans protected byte flags = 0x00; // TODO: Yogesh, this should be intialized and sent on wire only when // parallel wan is enabled private Long tailKey = 0L; public VersionTag versionTag; transient boolean inhibitDistribution; /** * Constructor to use when preparing to send putall data out */ public PutAllEntryData(EntryEventImpl event) { this.key = event.getKey(); this.value = event.getRawNewValueAsHeapObject(); Object oldValue = event.getRawOldValueAsHeapObject(); if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) { this.oldValue = null; } else { this.oldValue = oldValue; } this.op = event.getOperation(); this.eventID = event.getEventId(); this.tailKey = event.getTailKey(); this.versionTag = event.getVersionTag(); setNotifyOnly(!event.getInvokePRCallbacks()); setCallbacksInvoked(event.callbacksInvoked()); setPossibleDuplicate(event.isPossibleDuplicate()); setInhibitDistribution(event.getInhibitDistribution()); } /** * Constructor to use when receiving a putall from someone else */ public PutAllEntryData(DataInput in, EventID baseEventID, int idx, Version version, ByteArrayDataInput bytesIn) throws IOException, ClassNotFoundException { this.key = DataSerializer.readObject(in); byte flgs = in.readByte(); if ((flgs & IS_OBJECT) != 0) { this.value = DataSerializer.readObject(in); } else { byte[] bb = DataSerializer.readByteArray(in); if ((flgs & IS_CACHED_DESER) != 0) { this.value = new FutureCachedDeserializable(bb); } else { this.value = bb; } } this.oldValue = null; this.op = Operation.fromOrdinal(in.readByte()); this.flags = in.readByte(); if ((this.flags & FILTER_ROUTING) != 0) { this.filterRouting = (FilterRoutingInfo) DataSerializer.readObject(in); } if ((this.flags & VERSION_TAG) != 0) { boolean persistentTag = (this.flags & PERSISTENT_TAG) != 0; this.versionTag = VersionTag.create(persistentTag, in); } if (isUsedFakeEventId()) { this.eventID = new EventID(); InternalDataSerializer.invokeFromData(this.eventID, in); } else { this.eventID = new EventID(baseEventID, idx); } if ((this.flags & HAS_TAILKEY) != 0) { this.tailKey = DataSerializer.readLong(in); } } @Override public String toString() { StringBuilder sb = new StringBuilder(50); sb.append("(").append(getKey()).append(",").append(this.value).append(",") .append(getOldValue()); if (this.bucketId > 0) { sb.append(", b").append(this.bucketId); } if (versionTag != null) { sb.append(versionTag); // sb.append(",v").append(versionTag.getEntryVersion()).append(",rv"+versionTag.getRegionVersion()); } if (filterRouting != null) { sb.append(", ").append(filterRouting); } sb.append(")"); return sb.toString(); } void setSender(InternalDistributedMember sender) { if (this.versionTag != null) { this.versionTag.replaceNullIDs(sender); } } /** * Used to serialize this instances data to out. If changes are made to this method * make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure * that the callers to this method are backwards compatible by creating toDataPreXX methods for * them even if they are not changed. * Callers for this method are: * {@link PutAllMessage#toData(DataOutput)} * {@link PutAllPRMessage#toData(DataOutput)} * {@link RemotePutAllMessage#toData(DataOutput)} */ public void toData(final DataOutput out) throws IOException { Object key = this.key; final Object v = this.value; DataSerializer.writeObject(key, out); if (v instanceof byte[] || v == null) { out.writeByte(0); DataSerializer.writeByteArray((byte[]) v, out); } else if (v instanceof CachedDeserializable) { CachedDeserializable cd = (CachedDeserializable) v; out.writeByte(IS_CACHED_DESER); DataSerializer.writeByteArray(cd.getSerializedValue(), out); } else { out.writeByte(IS_CACHED_DESER); DataSerializer.writeObjectAsByteArray(v, out); } out.writeByte(this.op.ordinal); byte bits = this.flags; if (this.filterRouting != null) bits |= FILTER_ROUTING; if (this.versionTag != null) { bits |= VERSION_TAG; if (this.versionTag instanceof DiskVersionTag) { bits |= PERSISTENT_TAG; } } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled bits |= HAS_TAILKEY; out.writeByte(bits); if (this.filterRouting != null) { DataSerializer.writeObject(this.filterRouting, out); } if (this.versionTag != null) { InternalDataSerializer.invokeToData(this.versionTag, out); } if (isUsedFakeEventId()) { // fake event id should be serialized InternalDataSerializer.invokeToData(this.eventID, out); } // TODO: Yogesh, this should be conditional, // make sure that we sent it on wire only // when parallel wan is enabled DataSerializer.writeLong(this.tailKey, out); } /** * Returns the key */ public Object getKey() { return this.key; } /** * Returns the value */ public Object getValue(InternalCache cache) { Object result = this.value; if (result instanceof FutureCachedDeserializable) { FutureCachedDeserializable future = (FutureCachedDeserializable) result; result = future.create(cache); this.value = result; } return result; } /** * Returns the old value */ public Object getOldValue() { return this.oldValue; } public Long getTailKey() { return this.tailKey; } public void setTailKey(Long key) { this.tailKey = key; } /** * Returns the operation */ public Operation getOp() { return this.op; } public EventID getEventID() { return this.eventID; } /** * change event id for the entry * * @param eventId new event id */ public void setEventId(EventID eventId) { this.eventID = eventId; } /** * change bucket id for the entry * * @param bucketId new bucket id */ public void setBucketId(Integer bucketId) { this.bucketId = bucketId; } /** * get bucket id for the entry * * @return bucket id */ public Integer getBucketId() { return this.bucketId; } /** * change event id into fake event id The algorithm is to change the threadid into * bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original * thread id. * * @return wether current event id is fake or not new bucket id */ public boolean setFakeEventID() { if (bucketId.intValue() < 0) { return false; } if (!isUsedFakeEventId()) { // assign a fake big thread id. bucket id starts from 0. In order to distinguish // with other read thread, let bucket id starts from 1 in fake thread id long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId.intValue(), eventID.getThreadID()); this.eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID()); this.setUsedFakeEventId(true); } return true; } public boolean isUsedFakeEventId() { return (flags & USED_FAKE_EVENT_ID) != 0; } public void setUsedFakeEventId(boolean usedFakeEventId) { if (usedFakeEventId) { flags |= USED_FAKE_EVENT_ID; } else { flags &= ~(USED_FAKE_EVENT_ID); } } public boolean isNotifyOnly() { return (flags & NOTIFY_ONLY) != 0; } public void setNotifyOnly(boolean notifyOnly) { if (notifyOnly) { flags |= NOTIFY_ONLY; } else { flags &= ~(NOTIFY_ONLY); } } boolean isPossibleDuplicate() { return (this.flags & POSDUP) != 0; } public void setPossibleDuplicate(boolean possibleDuplicate) { if (possibleDuplicate) { flags |= POSDUP; } else { flags &= ~(POSDUP); } } public boolean isInhibitDistribution() { return this.inhibitDistribution; } public void setInhibitDistribution(boolean inhibitDistribution) { this.inhibitDistribution = inhibitDistribution; } public boolean isCallbacksInvoked() { return this.callbacksInvoked; } public void setCallbacksInvoked(boolean callbacksInvoked) { this.callbacksInvoked = callbacksInvoked; } } |
data class | Long method2 Feature envy3 Primitive obsession4 Data class5 Inappropriate use of comments6 Inconsistent formatting and naming conventions7 Duplicated code8 Inefficient data serialization handling9 Inconsistent use of flags and boolean variables | t | f | t | 0 | 15000 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DistributedPutAllOperation.java/#L274-L599 | 2 | 2592 | 15000 | major | ||
| 576 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IteratorVariableElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.BacktrackingContentAssistTestLanguage.iteratorVariable"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIdentifierParserRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cColonKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cTypeAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cTypeTypeExpParserRuleCall_1_1_0 = (RuleCall)cTypeAssignment_1_1.eContents().get(0); //iteratorVariable: // name=Identifier (':' type=TypeExp)?; @Override public ParserRule getRule() { return rule; } //name=Identifier (':' type=TypeExp)? public Group getGroup() { return cGroup; } //name=Identifier public Assignment getNameAssignment_0() { return cNameAssignment_0; } //Identifier public RuleCall getNameIdentifierParserRuleCall_0_0() { return cNameIdentifierParserRuleCall_0_0; } //(':' type=TypeExp)? public Group getGroup_1() { return cGroup_1; } //':' public Keyword getColonKeyword_1_0() { return cColonKeyword_1_0; } //type=TypeExp public Assignment getTypeAssignment_1_1() { return cTypeAssignment_1_1; } //TypeExp public RuleCall getTypeTypeExpParserRuleCall_1_1_0() { return cTypeTypeExpParserRuleCall_1_1_0; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 5781 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L2569-L2603 | 1 | 576 | 5781 | major | |
| 539 | {"result": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class MachOSymtab { /** * ByteBuffer holding the LC_SYMTAB command contents. */ private final ByteBuffer symtabCmd; private int symtabDataSize; private final ArrayList localSymbols = new ArrayList<>(); private final ArrayList globalSymbols = new ArrayList<>(); private final ArrayList undefSymbols = new ArrayList<>(); /** * Number of symbols added. */ private int symbolCount; /** * String holding symbol table strings. */ private final StringBuilder strTabContent = new StringBuilder(); /** * Keeps track of bytes in string table since strTabContent.length() is number of chars, not * bytes. */ private int strTabNrOfBytes = 0; MachOSymtab() { symtabCmd = MachOByteBuffer.allocate(symtab_command.totalsize); symtabCmd.putInt(symtab_command.cmd.off, symtab_command.LC_SYMTAB); symtabCmd.putInt(symtab_command.cmdsize.off, symtab_command.totalsize); symbolCount = 0; } static int getAlign() { return (4); } MachOSymbol addSymbolEntry(String name, byte type, byte secHdrIndex, long offset) { // Get the current symbol index and append symbol name to string table. int index; MachOSymbol sym; if (name.isEmpty()) { index = 0; strTabContent.append('\0'); strTabNrOfBytes += 1; sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); localSymbols.add(sym); } else { // We can't trust strTabContent.length() since that is // chars (UTF16), keep track of bytes on our own. index = strTabNrOfBytes; strTabContent.append("_").append(name).append('\0'); // + 1 for null, + 1 for "_" strTabNrOfBytes += (name.getBytes().length + 1 + 1); sym = new MachOSymbol(symbolCount, index, type, secHdrIndex, offset); switch (type) { case nlist_64.N_EXT: undefSymbols.add(sym); break; case nlist_64.N_SECT: case nlist_64.N_UNDF: // null symbol localSymbols.add(sym); break; case nlist_64.N_SECT | nlist_64.N_EXT: globalSymbols.add(sym); break; default: System.out.println("Unsupported Symbol type " + type); break; } } symbolCount++; return (sym); } void setOffset(int symoff) { symtabCmd.putInt(symtab_command.symoff.off, symoff); } // Update the symbol indexes once all symbols have been added. // This is required since we'll be reordering the symbols in the // file to be in the order of Local, global and Undefined. void updateIndexes() { int index = 0; // Update the local symbol indexes for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); sym.setIndex(index++); } // Update the global symbol indexes for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); sym.setIndex(index++); } // Update the undefined symbol indexes for (int i = index; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); sym.setIndex(index++); } } // Update LC_SYMTAB command fields based on the number of symbols added // return the file size taken up by symbol table entries and strings int calcSizes() { int stroff; stroff = symtabCmd.getInt(symtab_command.symoff.off) + (nlist_64.totalsize * symbolCount); symtabCmd.putInt(symtab_command.nsyms.off, symbolCount); symtabCmd.putInt(symtab_command.stroff.off, stroff); symtabCmd.putInt(symtab_command.strsize.off, strTabNrOfBytes); symtabDataSize = (nlist_64.totalsize * symbolCount) + strTabNrOfBytes; return (symtabDataSize); } int getNumLocalSyms() { return localSymbols.size(); } int getNumGlobalSyms() { return globalSymbols.size(); } int getNumUndefSyms() { return undefSymbols.size(); } byte[] getCmdArray() { return symtabCmd.array(); } // Create a single byte array that contains the symbol table entries // and string table byte[] getDataArray() { ByteBuffer symtabData = MachOByteBuffer.allocate(symtabDataSize); byte[] retarray; // Add the local symbols for (int i = 0; i < localSymbols.size(); i++) { MachOSymbol sym = localSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the global symbols for (int i = 0; i < globalSymbols.size(); i++) { MachOSymbol sym = globalSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the undefined symbols for (int i = 0; i < undefSymbols.size(); i++) { MachOSymbol sym = undefSymbols.get(i); byte[] arr = sym.getArray(); symtabData.put(arr); } // Add the stringtable byte[] strs = strTabContent.toString().getBytes(); symtabData.put(strs); retarray = symtabData.array(); return (retarray); } } |
data class | data class | t | t | t | 0 | 5502 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/macho/MachOSymtab.java/#L34-L209 | 1 | 539 | 5502 | minor | ||
| 1263 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | data class | t | t | t | 0 | 10524 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1263 | 10524 | minor | ||
| 792 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7536 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 792 | 7536 | minor | ||
| 600 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | data class | t | t | t | 0 | 5993 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 600 | 5993 | major | ||
| 2130 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13230 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 2130 | 13230 | major | ||
| 1928 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 12445 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 1928 | 12445 | major | ||
| 1992 | YES I found bad smells the bad smells are: 1. Long class, 2. Data class, 3. Getter and setter methods, 4. Duplicate code, 5. Lack of encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class EnsemblExonVO extends EnsemblDBBaseVO { @JsonProperty(value = "version") private Integer version; @JsonProperty(value = "assembly_name") private String assemblyName; @JsonProperty(value = "seq_region_name") private String seqRegionName; @JsonProperty(value = "strand") private String strand; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getAssemblyName() { return assemblyName; } public void setAssemblyName(String assemblyName) { this.assemblyName = assemblyName; } public String getSeqRegionName() { return seqRegionName; } public void setSeqRegionName(String seqRegionName) { this.seqRegionName = seqRegionName; } public String getStrand() { return strand; } public void setStrand(String strand) { this.strand = strand; } } |
data class | Long class, 2 Data class, 3 Getter and setter methods, 4 Duplicate code, 5 Lack of encapsulation | t | f | t | . Long class, 3. Getter and setter methods, 4. Duplicate code, 5. Lack of encapsulation. | 0 | 12687 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/controller/vo/externaldb/ensemblevo/EnsemblExonVO.java/#L40-L85 | 2 | 1992 | 12687 | major | |
| 314 | { "output": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | data class, long method | t | t | t | long method | 0 | 3227 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 1 | 314 | 3227 | major | |
| 4211 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 11086 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 4211 | 11086 | major | |
| 2337 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1. Data Class": "DCSerialField class seems to be a Data Class as it holds only data and has minimal behavior" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | 1. data class: dcserialfield class seems to be a data class as it holds only data and has minimal behavior | t | t | t | 0 | 14166 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 2337 | 14166 | minor | ||
| 1523 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11179 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 1523 | 11179 | minor | ||
| 1786 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11979 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 1786 | 11979 | minor | ||
| 2135 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method, 2 Feature envy, 3 Shotgun surgery, 4 Duplicate code | t | f | t | 2. Feature envy, 3. Shotgun surgery, 4. Duplicate code | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2135 | 13243 | major | |
| 431 | " YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public byte getByteAt(long index) { return addr.getJByteAt(baseOffset + index); } |
feature envy | Feature envy | t | f | t | 0 | 4279 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/Symbol.java/#L77-L79 | 2 | 431 | 4279 | minor | ||
| 2633 | YES I found bad smells the bad smells are: 1.Long method, 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method, 2Large parameter list, 3Magic numbers, 4Data class, 5Switch statement, 6Duplicate code | t | f | t | 2.Large parameter list, 3.Magic numbers, 4.Data class, 5.Switch statement, 6.Duplicate code. | 0 | 15109 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 2633 | 15109 | minor | |
| 880 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method, blob | t | t | t | blob | 0 | 8016 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 880 | 8016 | major | |
| 1291 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 10618 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 1291 | 10618 | critical | ||
| 1590 | { "output": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Provider createProvider(URI remoteURI, ProviderFutureFactory futureFactory) throws Exception { CompositeData composite = URISupport.parseComposite(remoteURI); Map options = composite.getParameters(); Map filtered = PropertyUtil.filterProperties(options, FAILOVER_OPTION_PREFIX); Map nested = PropertyUtil.filterProperties(filtered, FAILOVER_NESTED_OPTION_PREFIX_ADDON); Map providerOptions = PropertyUtil.filterProperties(options, "provider."); // If we have been given a futures factory to use then we ignore any URI options indicating // what to create and just go with what we are given. if (futureFactory == null) { // Create a configured ProviderFutureFactory for use by the resulting AmqpProvider futureFactory = ProviderFutureFactory.create(providerOptions); if (!providerOptions.isEmpty()) { String msg = "" + " Not all Provider options could be applied during Failover Provider creation." + " Check the options are spelled correctly." + " Unused parameters=[" + providerOptions + "]." + " This provider instance cannot be started."; throw new IllegalArgumentException(msg); } } FailoverProvider provider = new FailoverProvider(composite.getComponents(), nested, futureFactory); Map unused = PropertyUtil.setProperties(provider, filtered); if (!unused.isEmpty()) { String msg = "" + " Not all options could be set on the Failover provider." + " Check the options are spelled correctly." + " Unused parameters=[" + unused + "]." + " This Provider cannot be started."; throw new IllegalArgumentException(msg); } return provider; } |
long method | 1 Long Method | t | f | t | 0 | 11387 | https://github.com/apache/qpid-jms/blob/59f62b111687072fad3302fb4c6f91a389b4c0e6/qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProviderFactory.java/#L49-L85 | 1 | 1590 | 11387 | minor | ||
| 1486 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 11092 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1486 | 11092 | major | |
| 384 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3921 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 384 | 3921 | major | ||
| 1732 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Primitive obsession 5. Duplicate code 6. Magic numbers (e.g. 32) 7. Poor naming (e.g. variables like "ent" and "iter") 8. Indicators of complex or confusing logic (e.g. multiple if statements checking for different conditions) 9. Comments left in the code (e.g. promise to remove println) 10. Use of non-descriptive or ambiguous variable names (e.g. "dst" or "src") 11. Lack of proper exception handling (e.g. if (ent.getType() == LogEntry.Type.TXN) throws an unchecked exception). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
long method | Long method2 Feature envy 3 Data class4 Primitive obsession5 Duplicate code6 Magic numbers (eg 32)7 Poor naming (eg variables like "ent" and "iter")8 Indicators of complex or confusing logic (eg multiple if statements checking for different conditions)9 Comments left in the code (eg promise to remove println) | t | f | t | 0 | 11821 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 1732 | 11821 | critical | ||
| 1441 | YES I found bad smells the bad smells are: 1) Long method 2) Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | ) Long method2) Feature envy | t | f | t | 0 | 10974 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 2 | 1441 | 10974 | minor | ||
| 1142 | YES I found bad smells * 1. Long method * 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | Long method* 2 Feature envy | t | f | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 2 | 1142 | 10095 | critical | ||
| 2345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 2 | 2345 | 14192 | major | ||
| 569 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 569 | 5727 | major | ||
| 571 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DirContextType { private String name; private DirContextType(String name) { this.name = name; } public String toString() { return name; } /** * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); /** * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); } |
data class | data class | t | t | t | 0 | 5739 | https://github.com/spring-projects/spring-ldap/blob/6a9bde34811b87b5425c05068a31ff61d7e59170/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java/#L30-L50 | 1 | 571 | 5739 | major | ||
| 1745 | { "message": "YES I found bad smells", "bad smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 1745 | 11851 | major | ||
| 2227 | {"output": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | long method, data class | t | t | t | long method | 0 | 13578 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 2227 | 13578 | minor | |
| 679 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BeanIOIterator implements Iterator, Closeable { private BeanReader reader; private transient Object next; private transient Object forceNext; public BeanIOIterator(BeanReader reader) { this.reader = reader; this.next = next(); } @Override public void close() throws IOException { if (reader != null) { reader.close(); reader = null; } } @Override public boolean hasNext() { return next != null; } @Override public Object next() { Object answer = next; if (answer == null) { answer = reader.read(); // after read we may force a next if (forceNext != null) { answer = forceNext; forceNext = null; } } else { next = reader.read(); // after read we may force a next if (forceNext != null) { next = forceNext; forceNext = null; } } return answer; } @Override public void remove() { // noop } /** * Sets a custom object as the next, such as from a custom error handler */ public void setNext(Object next) { this.forceNext = next; } } |
data class | data class | t | t | t | 0 | 6586 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-beanio/src/main/java/org/apache/camel/dataformat/beanio/BeanIOIterator.java/#L25-L81 | 1 | 679 | 6586 | minor | ||
| 1677 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | 1 Long Method | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 1 | 1677 | 11648 | minor | ||
| 1294 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10624 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1294 | 10624 | minor | ||
| 387 | YES I found bad smells The bad smells are: 1. Long Method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long Method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 3944 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 387 | 3944 | critical | |
| 2296 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | 1. data class | t | t | t | 0 | 14009 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 2296 | 14009 | critical | ||
| 371 | { "message": "YES I found bad smells the bad smells are:", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 1 | 371 | 3852 | minor | |
| 2232 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | 1. data class | t | t | t | 0 | 13594 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 2232 | 13594 | major | ||
| 1124 | YES, I found bad smells. the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | Feature envy | t | f | t | 0 | 10000 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 2 | 1124 | 10000 | minor | ||
| 872 | YES I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Duplicate code 4. Repeated logic | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | Long method2 Long parameter list3 Duplicate code4 Repeated logic | t | f | t | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 2 | 872 | 7980 | minor | ||
| 5515 | YES I found bad smells the bad smells are: Long method, Feature envy, Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, Feature envy, Data class | t | f | t | Feature envy, Data class | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5515 | 4260 | critical | |
| 4998 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
data class | data class, long method | t | t | t | long method | 0 | 13726 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 4998 | 13726 | minor | |
| 764 | {"message": "YES I found bad smells", "bad smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "header") @XmlAccessorType(XmlAccessType.FIELD) public static class Header { @XmlAttribute private String key; @XmlAttribute private String type; @XmlValue private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
data class | data class | t | t | t | 0 | 7134 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-base/src/main/java/org/apache/camel/support/dump/MessageDump.java/#L41-L77 | 1 | 764 | 7134 | major | ||
| 3994 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | 1. data class | t | t | t | 0 | 10543 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 1 | 3994 | 10543 | major | ||
| 1028 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy 3. Primitive Obsession/Code duplication 4. Inconsistent Formatting/Inconsistent Naming Conventions 5. Poor exception handling 6. Lack of Comments/Documentation 7. Magic Numbers/Unreadable code 8. Poor Control Flow/Inconsistent Use of Logic Operators 9. Data Clumps 10. Shotgun Surgery 11. Inappropriate Error Messages/System.out use 12. Continual Redundancy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long Method2 Feature Envy 3 Primitive Obsession/Code duplication 4 Inconsistent Formatting/Inconsistent Naming Conventions 5 Poor exception handling 6 Lack of Comments/Documentation 7 Magic Numbers/Unreadable code 8 Poor Control Flow/Inconsistent Use of Logic Operators 9 Data Clumps | t | f | t | 0 | 9371 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1028 | 9371 | minor | ||
| 590 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) { AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(), // struct.context.getOffset()+1);//FIXME // AVASM // Not setting version here // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope(struct.enclosingType, struct.context, bindings); // // we can't resolve here since the perclause typically refers // to pointcuts // // defined in the aspect that we haven't told the // BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } |
long method | long method, data class | t | t | t | data class | 0 | 5890 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java/#L526-L584 | 1 | 590 | 5890 | major | |
| 3557 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 7777 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 3557 | 7777 | major | |
| 2325 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | blob, data class | t | t | t | blob | 0 | 14140 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 2325 | 14140 | minor | |
| 1555 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 1555 | 11276 | minor | ||
| 4398 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 4398 | 11629 | minor | ||
| 2020 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12785 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 2020 | 12785 | major | ||
| 958 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 958 | 8556 | minor | ||
| 522 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number 3. Feature envy 4. Inconsistent formatting 5. Indentation issue 6. Unnecessary variable declaration 7. Use of for loop instead of enhanced for loop 8. Unnecessary exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static ResumptionAction fromName(String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } for (int i = 0; i < PRIVATE_VALUES.length; i++) { if (name.equals(PRIVATE_VALUES[i].name)) { return PRIVATE_VALUES[i]; } } throw new IllegalArgumentException( String.format("Invalid ResumptionAction name: %s", name)); } |
feature envy | Long method2 Magic number3 Feature envy4 Inconsistent formatting5 Indentation issue6 Unnecessary variable declaration7 Use of for loop instead of enhanced for loop8 Unnecessary exception handling | t | f | t | 0 | 5419 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/ResumptionAction.java/#L79-L92 | 2 | 522 | 5419 | minor | ||
| 2406 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class without behavior 4. Inappropriate name for entity class 5. Inconsistent formatting and spacing | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | Long method2 Feature envy 3 Data class without behavior 4 Inappropriate name for entity class5 Inconsistent formatting and spacing | t | f | t | 0 | 14388 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 2 | 2406 | 14388 | minor | ||
| 1902 | {"message": "YES I found bad smells", "bad smells are": ["2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | 2. data class | t | t | f | data class | 0 | 12364 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 1902 | 12364 | minor | |
| 302 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface UpgradeRequest { /** * Add WebSocket Extension Configuration(s) to Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(ExtensionConfig... configs); /** * Add WebSocket Extension Configuration(s) to request * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @param configs the configuration(s) to add */ void addExtensions(String... configs); /** * Remove all headers from request. * @deprecated (no longer supported, as this can undo the required upgrade request headers) */ @Deprecated void clearHeaders(); /** * Get the list of Cookies on the Upgrade request * * @return the list of Cookies */ List getCookies(); /** * Get the list of WebSocket Extension Configurations for this Upgrade Request. * * This is merely the list of requested Extensions to use, see {@link UpgradeResponse#getExtensions()} for what was * negotiated * * @return the list of Extension configurations (in the order they were specified) */ List getExtensions(); /** * Get a specific Header value from Upgrade Request * * @param name the name of the header * @return the value of the header (null if header does not exist) */ String getHeader(String name); /** * Get the specific Header value, as an int, from the Upgrade Request. * * @param name the name of the header * @return the value of the header as an int (-1 if header does not exist) * @throws NumberFormatException if unable to parse value as an int. */ int getHeaderInt(String name); /** * Get the headers as a Map of keys to value lists. * * @return the headers */ Map> getHeaders(); /** * Get the specific header values (for multi-value headers) * * @param name the header name * @return the value list (null if no header exists) */ List getHeaders(String name); /** * The host of the Upgrade Request URI * * @return host of the request URI */ String getHost(); /** * The HTTP version used for this Upgrade Request * * As of RFC6455 (December 2011) this is always * HTTP/1.1 * * @return the HTTP Version used */ String getHttpVersion(); /** * The HTTP method for this Upgrade Request. * * As of RFC6455 (December 2011) this is always GET * * @return the HTTP method used */ String getMethod(); /** * The WebSocket Origin of this Upgrade Request * * See RFC6455: Section 10.2 for details. * * Equivalent to {@link #getHeader(String)} passed the "Origin" header. * * @return the Origin header */ String getOrigin(); /** * Returns a map of the query parameters of the request. * * @return a unmodifiable map of query parameters of the request. */ Map> getParameterMap(); /** * Get the WebSocket Protocol Version * * As of RFC6455, Jetty only supports version * 13 * * @return the WebSocket protocol version */ String getProtocolVersion(); /** * Get the Query String of the request URI. * * @return the request uri query string */ String getQueryString(); /** * Get the Request URI * * @return the request URI */ URI getRequestURI(); /** * Access the Servlet HTTP Session (if present) * * Note: Never present on a Client UpgradeRequest. * * @return the Servlet HTTPSession on server side UpgradeRequests */ Object getSession(); /** * Get the list of offered WebSocket sub-protocols. * * @return the list of offered sub-protocols */ List getSubProtocols(); /** * Get the User Principal for this request. * * Only applicable when using UpgradeRequest from server side. * * @return the user principal */ Principal getUserPrincipal(); /** * Test if a specific sub-protocol is offered * * @param test the sub-protocol to test for * @return true if sub-protocol exists on request */ boolean hasSubProtocol(String test); /** * Test if supplied Origin is the same as the Request * * @param test the supplied origin * @return true if the supplied origin matches the request origin */ boolean isOrigin(String test); /** * Test if connection is secure. * * @return true if connection is secure. */ boolean isSecure(); /** * Set the list of Cookies on the request * * @param cookies the cookies to use */ void setCookies(List cookies); /** * Set the list of WebSocket Extension configurations on the request. * @param configs the list of extension configurations */ void setExtensions(List configs); /** * Set a specific header with multi-value field * * Overrides any previous value for this named header * * @param name the name of the header * @param values the multi-value field */ void setHeader(String name, List values); /** * Set a specific header value * * Overrides any previous value for this named header * * @param name the header to set * @param value the value to set it to */ void setHeader(String name, String value); /** * Sets multiple headers on the request. * * Only sets those headers provided, does not remove * headers that exist on request and are not provided in the * parameter for this method. * * Convenience method vs calling {@link #setHeader(String, List)} multiple times. * * @param headers the headers to set */ void setHeaders(Map> headers); /** * Set the HTTP Version to use. * * As of RFC6455 (December 2011) this should always be * HTTP/1.1 * * @param httpVersion the HTTP version to use. */ void setHttpVersion(String httpVersion); /** * Set the HTTP method to use. * * As of RFC6455 (December 2011) this is always GET * * @param method the HTTP method to use. */ void setMethod(String method); /** * Set the Request URI to use for this request. * * Must be an absolute URI with scheme 'ws' or 'wss' * * @param uri the Request URI */ void setRequestURI(URI uri); /** * Set the Session associated with this request. * * Typically used to associate the Servlet HttpSession object. * * @param session the session object to associate with this request */ void setSession(Object session); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(List protocols); /** * Set the offered WebSocket Sub-Protocol list. * * @param protocols the offered sub-protocol list */ void setSubProtocols(String... protocols); } |
data class | long method, data class | t | t | t | long method | 0 | 3165 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-api/src/main/java/org/eclipse/jetty/websocket/api/UpgradeRequest.java/#L32-L323 | 1 | 302 | 3165 | major | |
| 19 | {"response": "YES I found bad smells", "detected_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int getSiblingIndexWithClassName(Element element, String className) { int index = 0; while (element != null) { element = (Element) element.getPreviousSibling(); if (element != null && Elements.hasClassName(className, element)) { ++index; } } return index; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 679 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/commons-gwt/src/main/java/org/eclipse/che/ide/util/dom/DomUtils.java/#L171-L180 | 1 | 19 | 679 | major | |
| 462 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Serializable getRoutingObject(EntryOperation opDetails) { Date date = (Date) opDetails.getKey(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); // if(true){ // return month; // } switch (month) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; default: return null; } } |
long method | 1. long method | t | t | t | 0 | 4467 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/fixed/SingleHopQuarterPartitionResolver.java/#L69-L107 | 1 | 462 | 4467 | minor | ||
| 1513 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 1 | 1513 | 11161 | major | |
| 1141 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void transform(XtendConstructor source, JvmGenericType container) { JvmConstructor constructor = typesFactory.createJvmConstructor(); container.getMembers().add(constructor); associator.associatePrimary(source, constructor); JvmVisibility visibility = source.getVisibility(); constructor.setSimpleName(container.getSimpleName()); constructor.setVisibility(visibility); for (XtendParameter parameter : source.getParameters()) { translateParameter(constructor, parameter); } copyAndFixTypeParameters(source.getTypeParameters(), constructor); for (JvmTypeReference exception : source.getExceptions()) { constructor.getExceptions().add(jvmTypesBuilder.cloneWithProxies(exception)); } translateAnnotationsTo(source.getAnnotations(), constructor); setBody(constructor, source.getExpression()); jvmTypesBuilder.copyDocumentationTo(source, constructor); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10090 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/src/org/eclipse/xtend/core/jvmmodel/XtendJvmModelInferrer.java/#L721-L738 | 2 | 1141 | 10090 | minor | |
| 2299 | { "output": "YES I found bad smells\nthe bad smells are:\n1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | \n1. long method | t | t | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 1 | 2299 | 14028 | major | ||
| 3326 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | blob, data class | t | t | t | blob | 0 | 6173 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 3326 | 6173 | critical | |
| 840 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | data class | t | t | t | 0 | 7789 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 840 | 7789 | minor | ||
| 2045 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inappropriate comments 6. Data class 7. Many parameters 8. Primitive obsession 9. Dead code 10. Null pointer exceptions 11. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Inappropriate comments6 Data class7 Many parameters8 Primitive obsession9 Dead code | t | f | t | 0 | 12871 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 2045 | 12871 | minor | ||
| 2115 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | long method, data class | t | t | t | data class | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 1 | 2115 | 13193 | minor | |
| 1842 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
long method | 1, Long Method | t | f | t | 1 | 0 | 12151 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 1 | 1842 | 12151 | major | |
| 130 | { "response": "YES I found bad smells", "bad smells are": [ "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ParseSpec withTimestampSpec(TimestampSpec spec) { return new TimeAndDimsParseSpec(spec, getDimensionsSpec()); } |
feature envy | feature envy | t | t | t | 0 | 1610 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/core/src/main/java/org/apache/druid/data/input/impl/TimeAndDimsParseSpec.java/#L70-L74 | 1 | 130 | 1610 | minor | ||
| 3676 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public WeightedAshwoodEntitySorter() { this.weightedDbEntityComparator = new WeightedDbEntityComparator(); this.weightedObjEntityComparator = new WeightedObjEntityComparator(); this.entityWeights = Collections.emptyMap(); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 8524 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/ashwood/WeightedAshwoodEntitySorter.java/#L42-L46 | 2 | 3676 | 8524 | major | |
| 5770 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14810 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5770 | 14810 | major | ||
| 1041 | YES I found bad smells The bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy. | 0 | 9429 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1041 | 9429 | minor | |
| 2687 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | Feature envy2 Long method | t | f | t | 0 | 15282 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 2687 | 15282 | minor | ||
| 1716 | YES, I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11781 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1716 | 11781 | major | ||
| 2400 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14379 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 2400 | 14379 | minor | |
| 2044 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 12869 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 2044 | 12869 | minor | |
| 190 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 2196 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 190 | 2196 | major | |
| 5760 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14516 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5760 | 14516 | minor | |
| 984 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | long method, blob | t | t | t | blob | 0 | 8875 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 1 | 984 | 8875 | minor | |
| 2317 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Temporary field 4. Shotgun surgery 5. Primitive obsession 6. Message chain 7. Inappropriate intimacy 8. Data clumps 9. Data class 10. Inconsistent naming convention 11. Deeply nested code 12. Feature envy between Map and PartitionCollapsingSchemas classes. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
data class | Long method2 Feature envy3 Temporary field4 Shotgun surgery5 Primitive obsession6 Message chain7 Inappropriate intimacy8 Data clumps9 Data class | t | f | t | 0 | 14122 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 2 | 2317 | 14122 | major | ||
| 1314 | YES I found bad smells the bad smells are: 1. Long method 2. Loss of cohesion | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | Long method2 Loss of cohesion | t | f | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 2 | 1314 | 10686 | minor | ||
| 16 | { "answer": "YES I found bad smells", "the bad smells are": "Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class | t | t | t | 0 | 642 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 16 | 642 | major | ||
| 2438 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | long method, data class | t | t | t | long method | 0 | 14474 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 1 | 2438 | 14474 | minor | |
| 1535 | {"response": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Graph extends GraphShapeElement { public enum Alignment { HORIZONTAL, VERTICAL } private List nodes = new ArrayList<>(); private Set edges = new HashSet<>(); private Set subgraphs = new HashSet<>(); private Alignment alignment = Alignment.VERTICAL; /** * Constructs a Graph that uses the specified GraphEventManager to handle * any user generated events on GraphElements. * * @param eventManager */ public Graph(GraphController graphController) { super(graphController); } /** * Adds an edge to the Graph and sets its parent to be this Graph. * * @param edge * the edge to add */ public void addEdge(GraphEdge edge) { edge.setParent(this); edges.add(edge); } /** * Adds a node to the Graph and sets its parent to be this Graph. * * @param node * the node to add */ public void addNode(GraphNode node) { node.setParent(this); nodes.add(node); } /** * Adds a subgraph to the Graph and sets its parent to be this Graph. * * @param subgraph * the subgraph to add */ public void addSubgraph(Graph subgraph) { subgraph.setParent(this); subgraphs.add(subgraph); } /** * Returns the alignment of the Graph. * * @return the alignment of the Graph */ public Alignment getAlignment() { return alignment; } /** * Returns the edges contained in the Graph. * * @return the edges contained in the Graph */ public Set getEdges() { return Collections.unmodifiableSet(edges); } /** * Returns the nodes contained in the Graph. * * @return the nodes contained in the Graph */ public List getNodes() { return Collections.unmodifiableList(nodes); } /** * Returns the subgraphs contained in the Graph. * * @return the subgraphs contained in the Graph */ public Set getSubgraphs() { return Collections.unmodifiableSet(subgraphs); } /** * Removes an edge from the Graph. * * @param edge * the edge to remove * @return true if the edge is removed from the Graph */ public boolean removeEdge(GraphEdge edge) { return edges.remove(edge); } /** * Removes a node from the Graph. * * @param node * the node to remove * @return true if the node is removed from the Graph */ public boolean removeNode(GraphNode node) { return nodes.remove(node); } /** * Removes a subgraph from the Graph. * * @param subgraph * the subgraph to remove * @return true if the subgraph is removed from the Graph */ public boolean removeSubgraph(Graph subgraph) { return subgraphs.remove(subgraph); } /** * Sets the alignment of the Graph. * * @param alignment * the new alignment */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } } |
blob | blob | t | t | t | 0 | 11218 | https://github.com/apache/incubator-taverna-workbench/blob/2b74964ac1ee22e56c5dad3321869d84f7052dcf/taverna-graph-model/src/main/java/org/apache/taverna/workbench/models/graph/Graph.java/#L30-L161 | 1 | 1535 | 11218 | minor | ||
| 1515 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11164 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1515 | 11164 | minor | ||
| 1949 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 12529 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 1949 | 12529 | major | |
| 466 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | long method | t | t | t | 0 | 4523 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 1 | 466 | 4523 | major | ||
| 1711 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ObjectInFolderListImpl extends AbstractExtensionData implements ObjectInFolderList { private static final long serialVersionUID = 1L; private List objects; private Boolean hasMoreItems = Boolean.FALSE; private BigInteger numItems; @Override public List getObjects() { if (objects == null) { objects = new ArrayList(0); } return objects; } public void setObjects(List objects) { this.objects = objects; } @Override public Boolean hasMoreItems() { return hasMoreItems; } public void setHasMoreItems(Boolean hasMoreItems) { this.hasMoreItems = hasMoreItems; } @Override public BigInteger getNumItems() { return numItems; } public void setNumItems(BigInteger numItems) { this.numItems = numItems; } @Override public String toString() { return "ObjectInFolder List [objects=" + objects + ", has more items=" + hasMoreItems + ", num items=" + numItems + "]" + super.toString(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11768 | https://github.com/apache/chemistry-opencmis/blob/ef8513d708e5e21710afe5cafb8b32a62a0ae532/chemistry-opencmis-commons/chemistry-opencmis-commons-impl/src/main/java/org/apache/chemistry/opencmis/commons/impl/dataobjects/ObjectInFolderListImpl.java/#L31-L75 | 1 | 1711 | 11768 | minor | |
| 309 | {"message": "YES, I found bad smells", "bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void m() { C c = new C(); E1 e1 = new E1(); E2 e2 = new E2(); c.foo(e1,e2.getClass()); } |
long method | blob, long method | t | t | t | blob | 0 | 3204 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/tests/bugs1611/pr336880/Second.java/#L4-L9 | 1 | 309 | 3204 | critical | |
| 57 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean hasMatchingKey(Node model1, Node model2) { return keyProvider.getKey(model1).equals(keyProvider.getKey(model2)); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 987 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/NodeStorage.java/#L626-L628 | 2 | 57 | 987 | major | |
| 83 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface CompilationIdentifier { enum Verbosity { /** * Only the unique identifier of the compilation. */ ID, /** * Only the name of the compilation unit. */ NAME, /** * {@link #ID} + a readable description. */ DETAILED } CompilationRequestIdentifier INVALID_COMPILATION_ID = new CompilationRequestIdentifier() { @Override public String toString() { return toString(Verbosity.DETAILED); } @Override public String toString(Verbosity verbosity) { return "InvalidCompilationID"; } @Override public CompilationRequest getRequest() { return null; } }; /** * This method is a shortcut for {@link #toString(Verbosity)} with {@link Verbosity#DETAILED}. */ @Override String toString(); /** * Creates a String representation for this compilation identifier with a given * {@link Verbosity}. */ String toString(Verbosity verbosity); } |
data class | data class, long method | t | t | t | long method | 0 | 1197 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/compiler/src/org.graalvm.compiler.core.common/src/org/graalvm/compiler/core/common/CompilationIdentifier.java/#L33-L80 | 1 | 83 | 1197 | major | |
| 257 | { "response": "YES, I found bad smells", "bad smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 2 | 257 | 2777 | minor | |
| 2132 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 13234 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 2132 | 13234 | minor | |
| 141 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void sequence(ISerializationContext context, EObject semanticObject) { EPackage epackage = semanticObject.eClass().getEPackage(); ParserRule rule = context.getParserRule(); Action action = context.getAssignedAction(); Set parameters = context.getEnabledBooleanParameters(); if (epackage == Bug250313Package.eINSTANCE) switch (semanticObject.eClass().getClassifierID()) { case Bug250313Package.CHILD1: sequence_Child1(context, (Child1) semanticObject); return; case Bug250313Package.CHILD2: sequence_Child2(context, (Child2) semanticObject); return; case Bug250313Package.MODEL: sequence_Model(context, (Model) semanticObject); return; } if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context)); } |
long method | long method | t | t | t | 0 | 1773 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/valueconverter/serializer/Bug250313SemanticSequencer.java/#L29-L49 | 1 | 141 | 1773 | minor | ||
| 623 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6248 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 623 | 6248 | minor | ||
| 970 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 8695 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 970 | 8695 | minor | ||
| 2385 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ConfigurationSettingsServiceSoapService extends SOAP11Service implements _ConfigurationSettingsServiceSoap { private static final QName PORT_QNAME = new QName( "http://schemas.microsoft.com/TeamFoundation/2005/06/WorkItemTracking/configurationSettingsService/03", "ConfigurationSettingsServiceSoapService"); private static final String ENDPOINT_PATH = "/tfs/DefaultCollection/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx"; public _ConfigurationSettingsServiceSoapService( final URI endpoint, final QName port) { super(endpoint, port); } public _ConfigurationSettingsServiceSoapService( final HttpClient client, URI endpoint, QName port) { super(client, endpoint, port); } /** * @return the qualified name of the WSDL port this service implementation can be used with */ public static QName getPortQName() { return _ConfigurationSettingsServiceSoapService.PORT_QNAME; } /** * @return the path part to use when constructing a URI to contact a host that provides this service */ public static String getEndpointPath() { return _ConfigurationSettingsServiceSoapService.ENDPOINT_PATH; } public String getWorkitemTrackingVersion() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion requestData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersion(); final SOAPRequest request = createSOAPRequest( "GetWorkitemTrackingVersion", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkitemTrackingVersion"); } }); final _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkitemTrackingVersionResponse(); executeSOAPRequest( request, "GetWorkitemTrackingVersionResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkitemTrackingVersionResult(); } public long getMaxAttachmentSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSize(); final SOAPRequest request = createSOAPRequest( "GetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "GetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxAttachmentSizeResult(); } public void setMaxAttachmentSize(final long maxSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSize( maxSize); final SOAPRequest request = createSOAPRequest( "SetMaxAttachmentSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxAttachmentSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxAttachmentSizeResponse(); executeSOAPRequest( request, "SetMaxAttachmentSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public boolean getInProcBuildCompletionNotificationAvailability() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailability(); final SOAPRequest request = createSOAPRequest( "GetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_GetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "GetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.isGetInProcBuildCompletionNotificationAvailabilityResult(); } public void setInProcBuildCompletionNotificationAvailability(final boolean isEnabled) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability requestData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailability( isEnabled); final SOAPRequest request = createSOAPRequest( "SetInProcBuildCompletionNotificationAvailability", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetInProcBuildCompletionNotificationAvailability"); } }); final _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse responseData = new _ConfigurationSettingsServiceSoap_SetInProcBuildCompletionNotificationAvailabilityResponse(); executeSOAPRequest( request, "SetInProcBuildCompletionNotificationAvailabilityResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getMaxBuildListSize() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSize(); final SOAPRequest request = createSOAPRequest( "GetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_GetMaxBuildListSizeResponse(); executeSOAPRequest( request, "GetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetMaxBuildListSizeResult(); } public void setMaxBuildListSize(final int maxBuildListSize) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetMaxBuildListSize requestData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSize( maxBuildListSize); final SOAPRequest request = createSOAPRequest( "SetMaxBuildListSize", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetMaxBuildListSize"); } }); final _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse responseData = new _ConfigurationSettingsServiceSoap_SetMaxBuildListSizeResponse(); executeSOAPRequest( request, "SetMaxBuildListSizeResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } public int getWorkItemQueryTimeout() throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeout(); final SOAPRequest request = createSOAPRequest( "GetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "GetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_GetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "GetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); return responseData.getGetWorkItemQueryTimeoutResult(); } public void setWorkItemQueryTimeout(final int workItemQueryTimeout) throws TransportException, SOAPFault { final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout requestData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeout( workItemQueryTimeout); final SOAPRequest request = createSOAPRequest( "SetWorkItemQueryTimeout", new SOAPMethodRequestWriter() { public void writeSOAPRequest( final XMLStreamWriter writer, final OutputStream out) throws XMLStreamException, IOException { requestData.writeAsElement( writer, "SetWorkItemQueryTimeout"); } }); final _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse responseData = new _ConfigurationSettingsServiceSoap_SetWorkItemQueryTimeoutResponse(); executeSOAPRequest( request, "SetWorkItemQueryTimeoutResponse", new SOAPMethodResponseReader() { public void readSOAPResponse( final XMLStreamReader reader, final InputStream in) throws XMLStreamException, IOException { responseData.readFromElement(reader); } }); } } |
blob | long method, blob, data class | t | t | t | long method, data class | 0 | 14347 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/workitemtracking/configurationsettingsservice/_03/_ConfigurationSettingsServiceSoapService.java/#L53-L439 | 1 | 2385 | 14347 | major | |
| 2217 | YES I found bad smells the bad smells are: 1. Duplicate code 2. Long method 3. Feature envy 4. Switch statement 5. Magic numbers 6. Improper exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Duplicate code2 Long method 3 Feature envy4 Switch statement 5 Magic numbers 6 Improper exception handling | t | f | t | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 2217 | 13539 | major | ||
| 4 | { "response": "YES I found bad smells", "the bad smells are": [ "Long method", "Long parameter list", "Data class", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
data class | 'Long method', 'Long parameter list', 'Data class', 'Feature envy' | t | t | f | {',L,o,n,g," ",m,e,t,h,o,d,',","," ",',L,o,n,g," ",p,a,r,a,m,e,t,e,r," ",l,i,s,t,',","," ",',D,a,t,a," ",c,l,a,s,s,',","," ",',F,e,a,t,u,r,e," ",e,n,v,y,'} | {',o,n,g," ",m,t,h,o,d,',","," ",',o,n,g," ",p,r,m,t,r," ",i,t,',","," ",',D,t," ",c,',","," ",',t,u,r," ",n,v,y,'} | 0 | 555 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 2 | 4 | 555 | minor |
| 121 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void formatElement(IProgressMonitor monitor) { FormatProcessorXML formatProcessor = new FormatProcessorXML(); formatProcessor.setProgressMonitor(monitor); formatProcessor.getFormatPreferences().setClearAllBlankLines(true); formatProcessor.formatModel(model); CleanupProcessorXML bla = new CleanupProcessorXML(); bla.getCleanupPreferences().setCompressEmptyElementTags(true); bla.cleanupModel(model); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 1534 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.webflow.ui.graph/src/org/springframework/ide/eclipse/webflow/ui/graph/WebflowEditor.java/#L578-L587 | 2 | 121 | 1534 | minor | |
| 2127 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | long method | t | t | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 1 | 2127 | 13223 | critical | ||
| 4088 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10777 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 4088 | 10777 | minor | ||
| 4081 | YES I found bad smells The bad smells are: 1. Long method 2. Switch statement 3. Duplicate code (using getPropertyMakerFor() to get ruleThickness) 4. Feature envy (calling multiple methods from pList) 5. Use of RuntimeException to handle an error 6. Unused variables (textShadow and letterSpacing) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
feature envy | Long method 2 Switch statement 3 Duplicate code (using getPropertyMakerFor() to get ruleThickness) 4 Feature envy (calling multiple methods from pList) 5 Use of RuntimeException to handle an error 6 Unused variables (textShadow and letterSpacing) | t | f | t | 0 | 10762 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 4081 | 10762 | major | ||
| 1335 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class DynamicPackageEntry { // public: // // DynamicPackageEntry() =default; DynamicPackageEntry(String package_name, int package_id) { this.package_name = package_name; this.package_id = package_id; } String package_name; int package_id = 0; } |
data class | data class | t | t | t | 0 | 10724 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/resources/src/main/java/org/robolectric/res/android/LoadedArsc.java/#L62-L75 | 1 | 1335 | 10724 | critical | ||
| 1618 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Useless comments 6. Lack of proper variable and function names 7. Complex code without proper explanation/comments 8. Inefficient code structure 9. Code repetition 10. Unnecessary complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
feature envy | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Useless comments6 Lack of proper variable and function names7 Complex code without proper explanation/comments8 Inefficient code structure9 Code repetition | t | f | t | 0 | 11476 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1618 | 11476 | major | ||
| 830 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | data class | t | t | t | 0 | 7736 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 1 | 830 | 7736 | minor | ||
| 2671 | public boolean isAlgParams() { return getCertificate().getPublicKey().getEncodedParams() != null; YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15212 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 2671 | 15212 | minor | ||
| 2013 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method, data class | t | t | t | data class | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2013 | 12755 | critical | |
| 489 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void appendXmlComparison1(SQLBuffer buf, String op, FilterValue lhs, FilterValue rhs) { boolean castrhs = false; Class rc = Filters.wrap(rhs.getType()); int type = 0; if (rhs.isConstant()) { type = getJDBCType(JavaTypes.getTypeCode(rc), false); castrhs = true; } appendXmlExists(buf, lhs); buf.append(" ").append(op).append(" "); buf.append("$"); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("]' PASSING "); appendXmlVar(buf, lhs); buf.append(", "); if (castrhs) appendCast(buf, rhs, type); else rhs.appendTo(buf); buf.append(" AS \""); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("\")"); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 4865 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DB2Dictionary.java/#L682-L717 | 2 | 489 | 4865 | minor | |
| 4219 | YES I found bad smells the bad smells are: 1. Long method 2. Repeated code 3. High complexity 4. Inappropriate levels of abstraction 5. Feature envy 6. Use of magic numbers (e.g. "TRUE" and "JKS") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Long method2 Repeated code3 High complexity 4 Inappropriate levels of abstraction 5 Feature envy6 Use of magic numbers (eg "TRUE" and "JKS") | t | f | t | 0 | 11111 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 4219 | 11111 | major | ||
| 1194 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10265 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 1194 | 10265 | minor | ||
| 641 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "realm") @XmlType public class RealmTO implements EntityTO, TemplatableTO { private static final long serialVersionUID = 516330662956254391L; private String key; private String name; private String parent; private String fullPath; private String accountPolicy; private String passwordPolicy; private final List actions = new ArrayList<>(); @XmlJavaTypeAdapter(XmlGenericMapAdapter.class) private final Map templates = new HashMap<>(); private final Set resources = new HashSet<>(); @Override public String getKey() { return key; } @Override public void setKey(final String key) { this.key = key; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getParent() { return parent; } public void setParent(final String parent) { this.parent = parent; } public String getFullPath() { return fullPath; } @PathParam("fullPath") public void setFullPath(final String fullPath) { this.fullPath = fullPath; } public String getAccountPolicy() { return accountPolicy; } public void setAccountPolicy(final String accountPolicy) { this.accountPolicy = accountPolicy; } public String getPasswordPolicy() { return passwordPolicy; } public void setPasswordPolicy(final String passwordPolicy) { this.passwordPolicy = passwordPolicy; } @XmlElementWrapper(name = "actions") @XmlElement(name = "action") @JsonProperty("actions") public List getActions() { return actions; } @JsonProperty @Override public Map getTemplates() { return templates; } @XmlElementWrapper(name = "resources") @XmlElement(name = "resource") @JsonProperty("resources") public Set getResources() { return resources; } } |
data class | data class | t | t | t | 0 | 6352 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/RealmTO.java/#L36-L132 | 1 | 641 | 6352 | critical | ||
| 9 | { "message": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 2 | 9 | 612 | minor | |
| 4535 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12036 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 4535 | 12036 | minor | ||
| 884 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | Long method,2 Feature envy | t | f | t | 2. Feature envy | 0 | 8035 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 2 | 884 | 8035 | minor | |
| 5012 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Tight coupling 5. Magic numbers 6. Dead code 7. Exception handling 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method 2 Duplicate code 3 Feature envy 4 Tight coupling 5 Magic numbers 6 Dead code 7 Exception handling 8 Lack of comments/documentation | t | f | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 5012 | 13779 | major | ||
| 1616 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:com.alibaba.otter.canal.protocol.RowChange) RowChangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } protected FieldAccessorTable internalGetFieldAccessorTable() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_fieldAccessorTable .ensureFieldAccessorsInitialized( RowChange.class, Builder.class); } // Construct using com.alibaba.otter.canal.protocol.CanalEntry.RowChange.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getRowDatasFieldBuilder(); getPropsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); tableId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); eventType_ = EventType.UPDATE; bitField0_ = (bitField0_ & ~0x00000002); isDdl_ = false; bitField0_ = (bitField0_ & ~0x00000004); sql_ = ""; bitField0_ = (bitField0_ & ~0x00000008); if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); } else { rowDatasBuilder_.clear(); } if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); } else { propsBuilder_.clear(); } ddlSchemaName_ = ""; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return CanalEntry.internal_static_com_alibaba_otter_canal_protocol_RowChange_descriptor; } public RowChange getDefaultInstanceForType() { return RowChange.getDefaultInstance(); } public RowChange build() { RowChange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public RowChange buildPartial() { RowChange result = new RowChange(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.tableId_ = tableId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.eventType_ = eventType_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.isDdl_ = isDdl_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sql_ = sql_; if (rowDatasBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = java.util.Collections.unmodifiableList(rowDatas_); bitField0_ = (bitField0_ & ~0x00000010); } result.rowDatas_ = rowDatas_; } else { result.rowDatas_ = rowDatasBuilder_.build(); } if (propsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020)) { props_ = java.util.Collections.unmodifiableList(props_); bitField0_ = (bitField0_ & ~0x00000020); } result.props_ = props_; } else { result.props_ = propsBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000010; } result.ddlSchemaName_ = ddlSchemaName_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RowChange) { return mergeFrom((RowChange)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RowChange other) { if (other == RowChange.getDefaultInstance()) return this; if (other.hasTableId()) { setTableId(other.getTableId()); } if (other.hasEventType()) { setEventType(other.getEventType()); } if (other.hasIsDdl()) { setIsDdl(other.getIsDdl()); } if (other.hasSql()) { bitField0_ |= 0x00000008; sql_ = other.sql_; onChanged(); } if (rowDatasBuilder_ == null) { if (!other.rowDatas_.isEmpty()) { if (rowDatas_.isEmpty()) { rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); } else { ensureRowDatasIsMutable(); rowDatas_.addAll(other.rowDatas_); } onChanged(); } } else { if (!other.rowDatas_.isEmpty()) { if (rowDatasBuilder_.isEmpty()) { rowDatasBuilder_.dispose(); rowDatasBuilder_ = null; rowDatas_ = other.rowDatas_; bitField0_ = (bitField0_ & ~0x00000010); rowDatasBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getRowDatasFieldBuilder() : null; } else { rowDatasBuilder_.addAllMessages(other.rowDatas_); } } } if (propsBuilder_ == null) { if (!other.props_.isEmpty()) { if (props_.isEmpty()) { props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); } else { ensurePropsIsMutable(); props_.addAll(other.props_); } onChanged(); } } else { if (!other.props_.isEmpty()) { if (propsBuilder_.isEmpty()) { propsBuilder_.dispose(); propsBuilder_ = null; props_ = other.props_; bitField0_ = (bitField0_ & ~0x00000020); propsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPropsFieldBuilder() : null; } else { propsBuilder_.addAllMessages(other.props_); } } } if (other.hasDdlSchemaName()) { bitField0_ |= 0x00000040; ddlSchemaName_ = other.ddlSchemaName_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RowChange parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RowChange) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long tableId_ ; /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public boolean hasTableId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public long getTableId() { return tableId_; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder setTableId(long value) { bitField0_ |= 0x00000001; tableId_ = value; onChanged(); return this; } /** * optional int64 tableId = 1; * * **tableId,由数据库产生* * */ public Builder clearTableId() { bitField0_ = (bitField0_ & ~0x00000001); tableId_ = 0L; onChanged(); return this; } private EventType eventType_ = EventType.UPDATE; /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public boolean hasEventType() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public EventType getEventType() { return eventType_; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder setEventType(EventType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; eventType_ = value; onChanged(); return this; } /** * optional .com.alibaba.otter.canal.protocol.EventType eventType = 2 [default = UPDATE]; * * **数据变更类型* * */ public Builder clearEventType() { bitField0_ = (bitField0_ & ~0x00000002); eventType_ = EventType.UPDATE; onChanged(); return this; } private boolean isDdl_ ; /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean hasIsDdl() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public boolean getIsDdl() { return isDdl_; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder setIsDdl(boolean value) { bitField0_ |= 0x00000004; isDdl_ = value; onChanged(); return this; } /** * optional bool isDdl = 10 [default = false]; * * ** 标识是否是ddl语句 * * */ public Builder clearIsDdl() { bitField0_ = (bitField0_ & ~0x00000004); isDdl_ = false; onChanged(); return this; } private Object sql_ = ""; /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public boolean hasSql() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public String getSql() { Object ref = sql_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { sql_ = s; } return s; } else { return (String) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public com.google.protobuf.ByteString getSqlBytes() { Object ref = sql_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); sql_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSql( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder clearSql() { bitField0_ = (bitField0_ & ~0x00000008); sql_ = getDefaultInstance().getSql(); onChanged(); return this; } /** * optional string sql = 11; * * ** ddl/query的sql语句 * * */ public Builder setSqlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; sql_ = value; onChanged(); return this; } private java.util.List rowDatas_ = java.util.Collections.emptyList(); private void ensureRowDatasIsMutable() { if (!((bitField0_ & 0x00000010) == 0x00000010)) { rowDatas_ = new java.util.ArrayList(rowDatas_); bitField0_ |= 0x00000010; } } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> rowDatasBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasList() { if (rowDatasBuilder_ == null) { return java.util.Collections.unmodifiableList(rowDatas_); } else { return rowDatasBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public int getRowDatasCount() { if (rowDatasBuilder_ == null) { return rowDatas_.size(); } else { return rowDatasBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData getRowDatas(int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.set(index, value); onChanged(); } else { rowDatasBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder setRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.set(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas(RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(value); onChanged(); } else { rowDatasBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData value) { if (rowDatasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRowDatasIsMutable(); rowDatas_.add(index, value); onChanged(); } else { rowDatasBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addRowDatas( int index, RowData.Builder builderForValue) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.add(index, builderForValue.build()); onChanged(); } else { rowDatasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder addAllRowDatas( Iterable values) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rowDatas_); onChanged(); } else { rowDatasBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder clearRowDatas() { if (rowDatasBuilder_ == null) { rowDatas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); } else { rowDatasBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public Builder removeRowDatas(int index) { if (rowDatasBuilder_ == null) { ensureRowDatasIsMutable(); rowDatas_.remove(index); onChanged(); } else { rowDatasBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder getRowDatasBuilder( int index) { return getRowDatasFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowDataOrBuilder getRowDatasOrBuilder( int index) { if (rowDatasBuilder_ == null) { return rowDatas_.get(index); } else { return rowDatasBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasOrBuilderList() { if (rowDatasBuilder_ != null) { return rowDatasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rowDatas_); } } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder() { return getRowDatasFieldBuilder().addBuilder( RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public RowData.Builder addRowDatasBuilder( int index) { return getRowDatasFieldBuilder().addBuilder( index, RowData.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.RowData rowDatas = 12; * * ** 一次数据库变更可能存在多行 * * */ public java.util.List getRowDatasBuilderList() { return getRowDatasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder> getRowDatasFieldBuilder() { if (rowDatasBuilder_ == null) { rowDatasBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< RowData, RowData.Builder, RowDataOrBuilder>( rowDatas_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); rowDatas_ = null; } return rowDatasBuilder_; } private java.util.List props_ = java.util.Collections.emptyList(); private void ensurePropsIsMutable() { if (!((bitField0_ & 0x00000020) == 0x00000020)) { props_ = new java.util.ArrayList(props_); bitField0_ |= 0x00000020; } } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> propsBuilder_; /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsList() { if (propsBuilder_ == null) { return java.util.Collections.unmodifiableList(props_); } else { return propsBuilder_.getMessageList(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public int getPropsCount() { if (propsBuilder_ == null) { return props_.size(); } else { return propsBuilder_.getCount(); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair getProps(int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessage(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.set(index, value); onChanged(); } else { propsBuilder_.setMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder setProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.set(index, builderForValue.build()); onChanged(); } else { propsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps(Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(value); onChanged(); } else { propsBuilder_.addMessage(value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair value) { if (propsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropsIsMutable(); props_.add(index, value); onChanged(); } else { propsBuilder_.addMessage(index, value); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addProps( int index, Pair.Builder builderForValue) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.add(index, builderForValue.build()); onChanged(); } else { propsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder addAllProps( Iterable values) { if (propsBuilder_ == null) { ensurePropsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, props_); onChanged(); } else { propsBuilder_.addAllMessages(values); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder clearProps() { if (propsBuilder_ == null) { props_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); onChanged(); } else { propsBuilder_.clear(); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Builder removeProps(int index) { if (propsBuilder_ == null) { ensurePropsIsMutable(); props_.remove(index); onChanged(); } else { propsBuilder_.remove(index); } return this; } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder getPropsBuilder( int index) { return getPropsFieldBuilder().getBuilder(index); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public PairOrBuilder getPropsOrBuilder( int index) { if (propsBuilder_ == null) { return props_.get(index); } else { return propsBuilder_.getMessageOrBuilder(index); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsOrBuilderList() { if (propsBuilder_ != null) { return propsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(props_); } } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder() { return getPropsFieldBuilder().addBuilder( Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public Pair.Builder addPropsBuilder( int index) { return getPropsFieldBuilder().addBuilder( index, Pair.getDefaultInstance()); } /** * repeated .com.alibaba.otter.canal.protocol.Pair props = 13; * * **预留扩展* * */ public java.util.List getPropsBuilderList() { return getPropsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder> getPropsFieldBuilder() { if (propsBuilder_ == null) { propsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Pair, Pair.Builder, PairOrBuilder>( props_, ((bitField0_ & 0x00000020) == 0x00000020), getParentForChildren(), isClean()); props_ = null; } return propsBuilder_; } private Object ddlSchemaName_ = ""; /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public boolean hasDdlSchemaName() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public String getDdlSchemaName() { Object ref = ddlSchemaName_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { ddlSchemaName_ = s; } return s; } else { return (String) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public com.google.protobuf.ByteString getDdlSchemaNameBytes() { Object ref = ddlSchemaName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (String) ref); ddlSchemaName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaName( String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder clearDdlSchemaName() { bitField0_ = (bitField0_ & ~0x00000040); ddlSchemaName_ = getDefaultInstance().getDdlSchemaName(); onChanged(); return this; } /** * optional string ddlSchemaName = 14; * * ** ddl/query的schemaName,会存在跨库ddl,需要保留执行ddl的当前schemaName * * */ public Builder setDdlSchemaNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; ddlSchemaName_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:com.alibaba.otter.canal.protocol.RowChange) } |
blob | blob, long method | t | t | t | long method | 0 | 11474 | https://github.com/alibaba/canal/blob/08167c95c767fd3c9879584c0230820a8476a7a7/protocol/src/main/java/com/alibaba/otter/canal/protocol/CanalEntry.java/#L8477-L9689 | 1 | 1616 | 11474 | critical | |
| 2288 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class | t | t | t | 0 | 13898 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2288 | 13898 | major | ||
| 2399 | { "message": "YES I found bad smells", "bad smells are": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class StableValue { private final T value; private final Assumption assumption; public StableValue(T value, String name) { this.value = value; this.assumption = Truffle.getRuntime().createAssumption(name); } public T getValue() { return value; } public Assumption getAssumption() { return assumption; } @Override public String toString() { return "[" + value + ", " + assumption + "]"; } } |
data class | 1. data class | t | t | t | 0 | 14378 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/StableValue.java/#L28-L50 | 1 | 2399 | 14378 | minor | ||
| 3902 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final public void DynamicExpression() throws ParseException { /*@bgen(jjtree) DynamicExpression */ AstDynamicExpression jjtn000 = new AstDynamicExpression(JJTDYNAMICEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(START_DYNAMIC_EXPRESSION); Expression(); jj_consume_token(RBRACE); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } |
long method | Long method | t | f | t | 0 | 10217 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/el/parser/ELParser.java/#L140-L168 | 2 | 3902 | 10217 | minor | ||
| 866 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7932 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 866 | 7932 | minor | ||
| 755 | YES I found bad smells. the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7047 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 | 2 | 755 | 7047 | minor | |
| 1729 | { "message": "YES I found bad smells", "the bad smells are:": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DockerRunDialog extends AzureTitleAreaDialogWrapper { private final String basePath; // TODO: move to util private static final String MISSING_ARTIFACT = "A web archive (.war) artifact has not been configured."; private static final String MISSING_IMAGE_WITH_TAG = "Please specify Image and Tag."; private static final String INVALID_DOCKER_FILE = "Please specify a valid docker file."; private static final String INVALID_CERT_PATH = "Please specify a valid certificate path."; private static final String INVALID_ARTIFACT_FILE = "The artifact name %s is invalid. " + "An artifact name may contain only the ASCII letters 'a' through 'z' (case-insensitive), " + "and the digits '0' through '9', '.', '-' and '_'."; private static final String REPO_LENGTH_INVALID = "The length of repository name must be at least one character " + "and less than 256 characters"; private static final String CANNOT_END_WITH_SLASH = "The repository name should not end with '/'"; private static final String REPO_COMPONENT_INVALID = "Invalid repository component: %s, should follow: %s"; private static final String TAG_LENGTH_INVALID = "The length of tag name must be no more than 128 characters"; private static final String TAG_INVALID = "Invalid tag: %s, should follow: %s"; private static final String MISSING_MODEL = "Configuration data model not initialized."; private static final String ARTIFACT_NAME_REGEX = "^[.A-Za-z0-9_-]+\\.(war|jar)$"; private static final String REPO_COMPONENTS_REGEX = "[a-z0-9]+(?:[._-][a-z0-9]+)*"; private static final String TAG_REGEX = "^[\\w]+[\\w.-]*$"; private static final int TAG_LENGTH = 128; private static final int REPO_LENGTH = 255; private static final String IMAGE_NAME_PREFIX = "localimage"; private static final String DEFAULT_TAG_NAME = "latest"; private static final String SELECT_DOCKER_FILE = "Browse..."; private DockerHostRunSetting dataModel; private Text txtDockerHost; private Text txtImageName; private Text txtTagName; private Button btnTlsEnabled; private FileSelector dockerFileSelector; private FileSelector certPathSelector; /** * Create the dialog. */ public DockerRunDialog(Shell parentShell, String basePath, String targetPath) { super(parentShell); setShellStyle(SWT.RESIZE | SWT.TITLE); this.basePath = basePath; dataModel = new DockerHostRunSetting(); dataModel.setTargetPath(targetPath); dataModel.setTargetName(FilenameUtils.getName(targetPath)); } /** * Create contents of the dialog. */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite composite = new Composite(area, SWT.NONE); composite.setLayout(new GridLayout(5, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); dockerFileSelector = new FileSelector(composite, SWT.NONE, false, SELECT_DOCKER_FILE, basePath, "Docker File"); dockerFileSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1)); Label lblDockerHost = new Label(composite, SWT.NONE); lblDockerHost.setText("Docker Host"); txtDockerHost = new Text(composite, SWT.BORDER); txtDockerHost.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); btnTlsEnabled = new Button(composite, SWT.CHECK); btnTlsEnabled.addListener(SWT.Selection, event -> onBtnTlsEnabledSelection()); btnTlsEnabled.setText("Enable TLS"); certPathSelector = new FileSelector(composite, SWT.NONE, true, "Browse...", null, "Cert Path"); certPathSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); Label lblImage = new Label(composite, SWT.NONE); lblImage.setText("Image Name"); txtImageName = new Text(composite, SWT.BORDER); txtImageName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Label lblTagName = new Label(composite, SWT.NONE); lblTagName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTagName.setText("Tag Name"); txtTagName = new Text(composite, SWT.BORDER); txtTagName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); setTitle("Run on Docker Host"); setMessage(""); // TOOD: specify the message. reset(); return area; } private void reset() { // set default dockerHost value if (Utils.isEmptyString(txtDockerHost.getText())) { try { txtDockerHost.setText(DefaultDockerClient.fromEnv().uri().toString()); } catch (DockerCertificateException e) { e.printStackTrace(); } } // set default Dockerfile path String defaultDockerFilePath = DockerUtil.getDefaultDockerFilePathIfExist(basePath); dockerFileSelector.setFilePath(defaultDockerFilePath); // set default image and tag DateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String date = df.format(new Date()); if (Utils.isEmptyString(txtImageName.getText())) { txtImageName.setText(String.format("%s-%s", IMAGE_NAME_PREFIX, date)); } if (Utils.isEmptyString(txtTagName.getText())) { txtTagName.setText(DEFAULT_TAG_NAME); } updateCertPathVisibility(); } private void onBtnTlsEnabledSelection() { updateCertPathVisibility(); } private void updateCertPathVisibility() { certPathSelector.setVisible(btnTlsEnabled.getSelection()); } /** * Create contents of the button bar. */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { this.getShell().layout(true, true); return this.getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); } @Override protected boolean isResizable() { return true; } @Override public boolean isHelpAvailable() { return false; } @Override protected void okPressed() { apply(); try { validate(); execute(); super.okPressed(); } catch (InvalidFormDataException e) { showErrorMessage("Error", e.getMessage()); } } private void apply() { dataModel.setTlsEnabled(btnTlsEnabled.getSelection()); dataModel.setDockerFilePath(dockerFileSelector.getFilePath()); dataModel.setDockerCertPath(certPathSelector.getFilePath()); dataModel.setDockerHost(txtDockerHost.getText()); dataModel.setImageName(txtImageName.getText()); dataModel.setTagName(txtTagName.getText()); } private void validate() throws InvalidFormDataException { if (dataModel == null) { throw new InvalidFormDataException(MISSING_MODEL); } // docker file if (Utils.isEmptyString(dataModel.getDockerFilePath())) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } File dockerFile = Paths.get(dataModel.getDockerFilePath()).toFile(); if (!dockerFile.exists() || !dockerFile.isFile()) { throw new InvalidFormDataException(INVALID_DOCKER_FILE); } // cert path if (dataModel.isTlsEnabled()) { if (Utils.isEmptyString(dataModel.getDockerCertPath())) { throw new InvalidFormDataException(INVALID_CERT_PATH); } File certPath = Paths.get(dataModel.getDockerCertPath()).toFile(); if (!certPath.exists() || !certPath.isDirectory()) { throw new InvalidFormDataException(INVALID_CERT_PATH); } } String imageName = dataModel.getImageName(); String tagName = dataModel.getTagName(); if (Utils.isEmptyString(imageName) || Utils.isEmptyString(tagName)) { throw new InvalidFormDataException(MISSING_IMAGE_WITH_TAG); } // check repository first if (imageName.length() < 1 || imageName.length() > REPO_LENGTH) { throw new InvalidFormDataException(REPO_LENGTH_INVALID); } if (imageName.endsWith("/")) { throw new InvalidFormDataException(CANNOT_END_WITH_SLASH); } final String[] repoComponents = imageName.split("/"); for (String component : repoComponents) { if (!component.matches(REPO_COMPONENTS_REGEX)) { throw new InvalidFormDataException( String.format(REPO_COMPONENT_INVALID, component, REPO_COMPONENTS_REGEX)); } } // check tag if (tagName.length() > TAG_LENGTH) { throw new InvalidFormDataException(TAG_LENGTH_INVALID); } if (!tagName.matches(TAG_REGEX)) { throw new InvalidFormDataException(String.format(TAG_INVALID, tagName, TAG_REGEX)); } // target package if (Utils.isEmptyString(dataModel.getTargetName())) { throw new InvalidFormDataException(MISSING_ARTIFACT); } if (!dataModel.getTargetName().matches(ARTIFACT_NAME_REGEX)) { throw new InvalidFormDataException(String.format(INVALID_ARTIFACT_FILE, dataModel.getTargetName())); } } private void execute() { Observable.fromCallable(() -> { ConsoleLogger.info("Starting job ... "); if (basePath == null) { ConsoleLogger.error("Project base path is null."); throw new FileNotFoundException("Project base path is null."); } // locate artifact to specified location String targetFilePath = dataModel.getTargetPath(); ConsoleLogger.info(String.format("Locating artifact ... [%s]", targetFilePath)); // validate dockerfile Path targetDockerfile = Paths.get(dataModel.getDockerFilePath()); ConsoleLogger.info(String.format("Validating dockerfile ... [%s]", targetDockerfile)); if (!targetDockerfile.toFile().exists()) { throw new FileNotFoundException("Dockerfile not found."); } // replace placeholder if exists String content = new String(Files.readAllBytes(targetDockerfile)); content = content.replaceAll(Constant.DOCKERFILE_ARTIFACT_PLACEHOLDER, Paths.get(basePath).toUri().relativize(Paths.get(targetFilePath).toUri()).getPath()); Files.write(targetDockerfile, content.getBytes()); // build image String imageNameWithTag = String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName()); ConsoleLogger.info(String.format("Building image ... [%s]", imageNameWithTag)); DockerClient docker = DockerUtil.getDockerClient(dataModel.getDockerHost(), dataModel.isTlsEnabled(), dataModel.getDockerCertPath()); DockerUtil.buildImage(docker, imageNameWithTag, targetDockerfile.getParent(), targetDockerfile.getFileName().toString(), new DockerProgressHandler()); // create a container ConsoleLogger.info(Constant.MESSAGE_CREATING_CONTAINER); String containerId = DockerUtil.createContainer(docker, String.format("%s:%s", dataModel.getImageName(), dataModel.getTagName())); ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_INFO, containerId)); // start container ConsoleLogger.info(Constant.MESSAGE_STARTING_CONTAINER); Container container = DockerUtil.runContainer(docker, containerId); DockerRuntime.getInstance().setRunningContainerId(basePath, container.id(), dataModel); // props String hostname = new URI(dataModel.getDockerHost()).getHost(); ImmutableList ports = container.ports(); String publicPort = null; if (ports != null) { for (Container.PortMapping portMapping : ports) { if (Constant.TOMCAT_SERVICE_PORT.equals(String.valueOf(portMapping.privatePort()))) { publicPort = String.valueOf(portMapping.publicPort()); } } } ConsoleLogger.info(String.format(Constant.MESSAGE_CONTAINER_STARTED, (hostname != null ? hostname : "localhost") + (publicPort != null ? ":" + publicPort : ""))); return null; }).subscribeOn(SchedulerProviderFactory.getInstance().getSchedulerProvider().io()).subscribe( ret -> { ConsoleLogger.info("Container started."); sendTelemetry(true, null); }, e -> { e.printStackTrace(); ConsoleLogger.error(e.getMessage()); sendTelemetry(false, e.getMessage()); } ); } // TODO: refactor later private void sendTelemetry(boolean success, @Nullable String errorMsg) { Map map = new HashMap<>(); map.put("Success", String.valueOf(success)); if (null != dataModel.getTargetName()) { map.put("FileType", FilenameUtils.getExtension(dataModel.getTargetName())); } else { map.put("FileType", ""); } if (!success) { map.put("ErrorMsg", errorMsg); } AppInsightsClient.createByType(AppInsightsClient.EventType.Action, "Docker", "Run", map); } private void showErrorMessage(String title, String message) { MessageDialog.openError(this.getShell(), title, message); } } |
blob | blob, long method | t | t | t | long method | 0 | 11813 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/PluginsAndFeatures/azure-toolkit-for-eclipse/com.microsoft.azuretools.container/src/main/java/com/microsoft/azuretools/container/ui/DockerRunDialog.java/#L73-L399 | 1 | 1729 | 11813 | major | |
| 2073 | { "response": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ZoneOffsetTransitionRule implements Serializable { /** * Serialization version. */ private static final long serialVersionUID = 6889046316657758795L; /** * The month of the month-day of the first day of the cutover week. * The actual date will be adjusted by the dowChange field. */ private final Month month; /** * The day-of-month of the month-day of the cutover week. * If positive, it is the start of the week where the cutover can occur. * If negative, it represents the end of the week where cutover can occur. * The value is the number of days from the end of the month, such that * {@code -1} is the last day of the month, {@code -2} is the second * to last day, and so on. */ private final byte dom; /** * The cutover day-of-week, null to retain the day-of-month. */ private final DayOfWeek dow; /** * The cutover time in the 'before' offset. */ private final LocalTime time; /** * Whether the cutover time is midnight at the end of day. */ private final boolean timeEndOfDay; /** * The definition of how the local time should be interpreted. */ private final TimeDefinition timeDefinition; /** * The standard offset at the cutover. */ private final ZoneOffset standardOffset; /** * The offset before the cutover. */ private final ZoneOffset offsetBefore; /** * The offset after the cutover. */ private final ZoneOffset offsetAfter; /** * Obtains an instance defining the yearly rule to create transitions between two offsets. * * Applications should normally obtain an instance from {@link ZoneRules}. * This factory is only intended for use when creating {@link ZoneRules}. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @return the rule, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight * @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value */ public static ZoneOffsetTransitionRule of( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { Objects.requireNonNull(month, "month"); Objects.requireNonNull(time, "time"); Objects.requireNonNull(timeDefnition, "timeDefnition"); Objects.requireNonNull(standardOffset, "standardOffset"); Objects.requireNonNull(offsetBefore, "offsetBefore"); Objects.requireNonNull(offsetAfter, "offsetAfter"); if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); } if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); } if (time.getNano() != 0) { throw new IllegalArgumentException("Time's nano-of-second must be zero"); } return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter); } /** * Creates an instance defining the yearly rule to create transitions between two offsets. * * @param month the month of the month-day of the first day of the cutover week, not null * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that * day or later, negative if the week is that day or earlier, counting from the last day of the month, * from -28 to 31 excluding 0 * @param dayOfWeek the required day-of-week, null if the month-day should not be changed * @param time the cutover time in the 'before' offset, not null * @param timeEndOfDay whether the time is midnight at the end of day * @param timeDefnition how to interpret the cutover * @param standardOffset the standard offset in force at the cutover, not null * @param offsetBefore the offset before the cutover, not null * @param offsetAfter the offset after the cutover, not null * @throws IllegalArgumentException if the day of month indicator is invalid * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight */ ZoneOffsetTransitionRule( Month month, int dayOfMonthIndicator, DayOfWeek dayOfWeek, LocalTime time, boolean timeEndOfDay, TimeDefinition timeDefnition, ZoneOffset standardOffset, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { assert time.getNano() == 0; this.month = month; this.dom = (byte) dayOfMonthIndicator; this.dow = dayOfWeek; this.time = time; this.timeEndOfDay = timeEndOfDay; this.timeDefinition = timeDefnition; this.standardOffset = standardOffset; this.offsetBefore = offsetBefore; this.offsetAfter = offsetAfter; } //----------------------------------------------------------------------- /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } /** * Writes the object using a * dedicated serialized form. * @serialData * Refer to the serialized form of * ZoneRules.writeReplace * for the encoding of epoch seconds and offsets. * {@code * * out.writeByte(3); // identifies a ZoneOffsetTransition * final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); * final int stdOffset = standardOffset.getTotalSeconds(); * final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; * final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; * final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); * final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); * final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); * final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); * final int dowByte = (dow == null ? 0 : dow.getValue()); * int b = (month.getValue() << 28) + // 4 bits * ((dom + 32) << 22) + // 6 bits * (dowByte << 19) + // 3 bits * (timeByte << 14) + // 5 bits * (timeDefinition.ordinal() << 12) + // 2 bits * (stdOffsetByte << 4) + // 8 bits * (beforeByte << 2) + // 2 bits * afterByte; // 2 bits * out.writeInt(b); * if (timeByte == 31) { * out.writeInt(timeSecs); * } * if (stdOffsetByte == 255) { * out.writeInt(stdOffset); * } * if (beforeByte == 3) { * out.writeInt(offsetBefore.getTotalSeconds()); * } * if (afterByte == 3) { * out.writeInt(offsetAfter.getTotalSeconds()); * } * } * * * @return the replacing object, not null */ private Object writeReplace() { return new Ser(Ser.ZOTRULE, this); } /** * Writes the state to the stream. * * @param out the output stream, not null * @throws IOException if an error occurs */ void writeExternal(DataOutput out) throws IOException { final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); final int stdOffset = standardOffset.getTotalSeconds(); final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset; final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset; final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31); final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255); final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3); final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3); final int dowByte = (dow == null ? 0 : dow.getValue()); int b = (month.getValue() << 28) + // 4 bits ((dom + 32) << 22) + // 6 bits (dowByte << 19) + // 3 bits (timeByte << 14) + // 5 bits (timeDefinition.ordinal() << 12) + // 2 bits (stdOffsetByte << 4) + // 8 bits (beforeByte << 2) + // 2 bits afterByte; // 2 bits out.writeInt(b); if (timeByte == 31) { out.writeInt(timeSecs); } if (stdOffsetByte == 255) { out.writeInt(stdOffset); } if (beforeByte == 3) { out.writeInt(offsetBefore.getTotalSeconds()); } if (afterByte == 3) { out.writeInt(offsetAfter.getTotalSeconds()); } } /** * Reads the state from the stream. * * @param in the input stream, not null * @return the created object, not null * @throws IOException if an error occurs */ static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException { int data = in.readInt(); Month month = Month.of(data >>> 28); int dom = ((data & (63 << 22)) >>> 22) - 32; int dowByte = (data & (7 << 19)) >>> 19; DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte); int timeByte = (data & (31 << 14)) >>> 14; TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12]; int stdByte = (data & (255 << 4)) >>> 4; int beforeByte = (data & (3 << 2)) >>> 2; int afterByte = (data & 3); LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0)); ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900)); ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800)); ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800)); return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after); } //----------------------------------------------------------------------- /** * Gets the month of the transition. * * If the rule defines an exact date then the month is the month of that date. * * If the rule defines a week where the transition might occur, then the month * if the month of either the earliest or latest possible date of the cutover. * * @return the month of the transition, not null */ public Month getMonth() { return month; } /** * Gets the indicator of the day-of-month of the transition. * * If the rule defines an exact date then the day is the month of that date. * * If the rule defines a week where the transition might occur, then the day * defines either the start of the end of the transition week. * * If the value is positive, then it represents a normal day-of-month, and is the * earliest possible date that the transition can be. * The date may refer to 29th February which should be treated as 1st March in non-leap years. * * If the value is negative, then it represents the number of days back from the * end of the month where {@code -1} is the last day of the month. * In this case, the day identified is the latest possible date that the transition can be. * * @return the day-of-month indicator, from -28 to 31 excluding 0 */ public int getDayOfMonthIndicator() { return dom; } /** * Gets the day-of-week of the transition. * * If the rule defines an exact date then this returns null. * * If the rule defines a week where the cutover might occur, then this method * returns the day-of-week that the month-day will be adjusted to. * If the day is positive then the adjustment is later. * If the day is negative then the adjustment is earlier. * * @return the day-of-week that the transition occurs, null if the rule defines an exact date */ public DayOfWeek getDayOfWeek() { return dow; } /** * Gets the local time of day of the transition which must be checked with * {@link #isMidnightEndOfDay()}. * * The time is converted into an instant using the time definition. * * @return the local time of day of the transition, not null */ public LocalTime getLocalTime() { return time; } /** * Is the transition local time midnight at the end of day. * * The transition may be represented as occurring at 24:00. * * @return whether a local time of midnight is at the start or end of the day */ public boolean isMidnightEndOfDay() { return timeEndOfDay; } /** * Gets the time definition, specifying how to convert the time to an instant. * * The local time can be converted to an instant using the standard offset, * the wall offset or UTC. * * @return the time definition, not null */ public TimeDefinition getTimeDefinition() { return timeDefinition; } /** * Gets the standard offset in force at the transition. * * @return the standard offset, not null */ public ZoneOffset getStandardOffset() { return standardOffset; } /** * Gets the offset before the transition. * * @return the offset before, not null */ public ZoneOffset getOffsetBefore() { return offsetBefore; } /** * Gets the offset after the transition. * * @return the offset after, not null */ public ZoneOffset getOffsetAfter() { return offsetAfter; } //----------------------------------------------------------------------- /** * Creates a transition instance for the specified year. * * Calculations are performed using the ISO-8601 chronology. * * @param year the year to create a transition for, not null * @return the transition instance, not null */ public ZoneOffsetTransition createTransition(int year) { LocalDate date; if (dom < 0) { date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom); if (dow != null) { date = date.with(previousOrSame(dow)); } } else { date = LocalDate.of(year, month, dom); if (dow != null) { date = date.with(nextOrSame(dow)); } } if (timeEndOfDay) { date = date.plusDays(1); } LocalDateTime localDT = LocalDateTime.of(date, time); LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore); return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter); } //----------------------------------------------------------------------- /** * Checks if this object equals another. * * The entire state of the object is compared. * * @param otherRule the other object to compare to, null returns false * @return true if equal */ @Override public boolean equals(Object otherRule) { if (otherRule == this) { return true; } if (otherRule instanceof ZoneOffsetTransitionRule) { ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; return month == other.month && dom == other.dom && dow == other.dow && timeDefinition == other.timeDefinition && time.equals(other.time) && timeEndOfDay == other.timeEndOfDay && standardOffset.equals(other.standardOffset) && offsetBefore.equals(other.offsetBefore) && offsetAfter.equals(other.offsetAfter); } return false; } /** * Returns a suitable hash code. * * @return the hash code */ @Override public int hashCode() { int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + (month.ordinal() << 11) + ((dom + 32) << 5) + ((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal()); return hash ^ standardOffset.hashCode() ^ offsetBefore.hashCode() ^ offsetAfter.hashCode(); } //----------------------------------------------------------------------- /** * Returns a string describing this object. * * @return a string for debugging, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("TransitionRule[") .append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ") .append(offsetBefore).append(" to ").append(offsetAfter).append(", "); if (dow != null) { if (dom == -1) { buf.append(dow.name()).append(" on or before last day of ").append(month.name()); } else if (dom < 0) { buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name()); } else { buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom); } } else { buf.append(month.name()).append(' ').append(dom); } buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString()) .append(" ").append(timeDefinition) .append(", standard offset ").append(standardOffset) .append(']'); return buf.toString(); } //----------------------------------------------------------------------- /** * A definition of the way a local time can be converted to the actual * transition date-time. * * Time zone rules are expressed in one of three ways: * * Relative to UTC * Relative to the standard offset in force * Relative to the wall offset (what you would see on a clock on the wall) * */ public static enum TimeDefinition { /** The local date-time is expressed in terms of the UTC offset. */ UTC, /** The local date-time is expressed in terms of the wall offset. */ WALL, /** The local date-time is expressed in terms of the standard offset. */ STANDARD; /** * Converts the specified local date-time to the local date-time actually * seen on a wall clock. * * This method converts using the type of this enum. * The output is defined relative to the 'before' offset of the transition. * * The UTC type uses the UTC offset. * The STANDARD type uses the standard offset. * The WALL type returns the input date-time. * The result is intended for use with the wall-offset. * * @param dateTime the local date-time, not null * @param standardOffset the standard offset, not null * @param wallOffset the wall offset, not null * @return the date-time relative to the wall/before offset, not null */ public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { switch (this) { case UTC: { int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); return dateTime.plusSeconds(difference); } case STANDARD: { int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); return dateTime.plusSeconds(difference); } default: // WALL return dateTime; } } } } |
data class | data class, long method | t | t | t | long method | 0 | 13034 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java/#L100-L632 | 1 | 2073 | 13034 | minor | |
| 2511 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | blob, data class | t | t | t | blob | 0 | 14687 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 1 | 2511 | 14687 | major | |
| 2390 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Cel4rreg { long seghigh; long seglow; int p_dsafmt = -1; long p_dsaptr; RegisterSet regs; /** * Creates the instance and attempts to locate the registers. */ Cel4rreg() { /* Debug option - before we do anything else, try using the old svcdump code */ String useSvcdump = System.getProperty("zebedee.use.svcdump"); if (useSvcdump != null && useSvcdump.equals("true")) { getRegistersFromSvcdump(); return; } /* * Try and get the registers from the following locations: * * 1) RTM2 work area * 2) BPXGMSTA service * 3) linkage stack entries * 4) TCB * 5) Usta * * if any succeeds we return otherwise move to the next location. */ int whereCount = 0; try { if ((regs = getRegistersFromRTM2()) != null && whereCount++ >= whereSkip) { whereFound = "RTM2"; failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } /* If we still have not found a dsa, invoke kernel svs */ try { if ((regs = getRegistersFromBPXGMSTA()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (whereFound == null) whereFound = "BPXGMSTA"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { //throw new Error("oops: " + e); } try { if ((regs = getRegistersFromLinkageStack()) != null && whereCount++ >= whereSkip) { whereFound = "Linkage"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "Cel4rreg","Unexepected exception", e); throw new Error("Unexpected IOException: " + e); } try { if ((regs = getRegistersFromTCB()) != null && whereCount++ >= whereSkip) { whereFound = "TCB"; if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { throw new Error("oops: " + e); } try { if (is64bit) { /* This is from celqrreg.plx370: "Get the save R4 from a NOSTACK call" */ long lca = CeexlaaTemplate.getCeelaa_lca64(inputStream, laa); p_dsaptr = CeelcaTemplate.getCeelca_savstack(inputStream, lca); log.fine("p_dsaptr from lca = " + hex(p_dsaptr)); p_dsafmt = stackdirection = CEECAASTACK_DOWN; if (validateDSA() == 0 && whereCount++ >= whereSkip) { whereFound = "LCA"; return; } } } catch (IOException e) { throw new Error("oops: " + e); } /* Last ditch */ try { if ((regs = getRegistersFromUsta()) != null && whereCount++ >= whereSkip) { whereFound = regs.whereFound(); if (tcb.tcbcmp() != 0) failingRegisters = regs; registers = regs; return; } } catch (IOException e) { } whereFound = "not found"; } /** * Try and get the registers from the RTM2 work area. Returns null if none found. As a * side-effect it also sets the stackdirection. */ private RegisterSet getRegistersFromRTM2() throws IOException { int level = ceecaalevel(); log.finer("caa level is " + level); /* If the CAA level is 13 or greater, get stack direction from * CAA. For older releases or the dummy CAA, default stack * direction to UP. */ if (is64bit) { /* Always use downstack in 64-bit mode? */ stackdirection = CEECAASTACK_DOWN; log.finer("stack direction is down"); } else if (level >= 13) { /* If LE 2.10 or higher */ /* Obtain dsa format from the CAA */ stackdirection = ceecaa_stackdirection(); log.finer("stack direction is " + (stackdirection == CEECAASTACK_UP ? "up" : "down")); } else { stackdirection = CEECAASTACK_UP; log.finer("stack direction is up"); } if ((stackdirection == CEECAASTACK_DOWN) && !is64bit) { try { long tempptr = ceecaasmcb(); //the ceecaasmcb call is not currently supported for 64 bit CAAs seghigh = SmcbTemplate.getSmcb_dsbos(inputStream, tempptr); seglow = CeexstkhTemplate.getStkh_stackfloor(inputStream, seghigh); } catch (Exception e) { //throw new Error("oops: " + e); return null; } } /* At this point, a valid CAA has been obtained. Access the RTM2 to obtain the DSA. */ long rtm2ptr = tcb.tcbrtwa(); if (rtm2ptr != 0) { try { log.finer("found some rtm2 registers"); RegisterSet regs = new RegisterSet(); long rtm2grs = rtm2ptr + Ihartm2aTemplate.getRtm2ereg$offset(); long rtm2grshi = rtm2ptr + Ihartm2aTemplate.getRtm2g64h$offset(); for (int i = 0; i < 16; i++) { long low = space.readUnsignedInt(rtm2grs + i*4); long high = is64bit ? space.readUnsignedInt(rtm2grshi + i*4) : 0; regs.setRegister(i, (high << 32) | low); } long rtm2psw = rtm2ptr + Ihartm2aTemplate.getRtm2apsw$offset(); regs.setPSW(space.readLong(rtm2psw)); if (registersValid(regs)) { log.finer("found good dsa in rtm2"); } else { log.finer("bad dsa in rtm2"); regs = null; } return regs; } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } } else { log.finer("failed to get registers from rtm2"); return null; } } /** * Validates the given register set with retry for down stack */ private boolean registersValid(RegisterSet regs) throws IOException { if (regs == null) return false; p_dsafmt = stackdirection; if (p_dsafmt == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } int lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } else { if (stackdirection == CEECAASTACK_DOWN) { p_dsaptr = regs.getRegisterAsAddress(13); log.finer("p_dsaptr from reg 13 (again) = " + hex(p_dsaptr)); p_dsafmt = CEECAASTACK_UP; lastrc = validateDSA(); if (lastrc == WARNING) { lastrc = validateDSA(); if (lastrc == 0) { log.finer("found valid dsa"); return true; } } } /* reset values */ log.finer("p_dsaptr invalid so reset: " + hex(p_dsaptr)); p_dsaptr = 0; } return false; } /** * Try and get the registers from the BPXGMSTA service. */ private RegisterSet getRegistersFromBPXGMSTA() throws IOException { RegisterSet regs = tcb.getRegistersFromBPXGMSTA(); if (is64bit) // celqrreg appears to always assume down stack stackdirection = CEECAASTACK_DOWN; if (registersValid(regs)) { log.finer("found good dsa in BPXGMSTA"); return regs; } else { log.finer("BPX registers are invalid so keep looking"); return null; } } /** * Try and get the registers from the linkage stack. */ private RegisterSet getRegistersFromLinkageStack() throws IOException { log.finer("enter getRegistersFromLinkageStack"); try { Lse[] linkageStack = tcb.getLinkageStack(); /* If Linkage stack is empty, leave */ if (linkageStack.length == 0) { log.finer("empty linkage stack"); return null; } for (int i = 0; i < linkageStack.length; i++) { Lse lse = linkageStack[i]; if (lse.lses1pasn() == space.getAsid()) { RegisterSet regs = new RegisterSet(); if (lse.isZArchitecture() && (lse.lses1typ7() == Lse.LSED1PC || lse.lses1typ7() == Lse.LSED1BAKR)) { log.finer("found some z arch registers"); regs.setPSW(lse.lses1pswh()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lses1grs(j)); } } else { log.finer("found some non z arch registers"); regs.setPSW(lse.lsespsw()); for (int j = 0; j < 16; j++) { regs.setRegister(j, lse.lsesgrs(j)); } } if (registersValid(regs)) { log.finer("found good dsa in linkage stack"); return regs; } } else { log.finer("different asid: " + hex(lse.lses1pasn())); } } } catch (IOException e) { throw e; } catch (Exception e) { throw new Error("oops: " + e); } log.finer("could not find registers in linkage stack"); return null; } /** * Try and get the registers from the TCB. */ private RegisterSet getRegistersFromTCB() throws IOException { log.finer("getRegistersFromTCB"); RegisterSet regs = tcb.getRegisters(); if (registersValid(regs)) { log.finer("found good dsa in TCB"); return regs; } else { return null; } } /** * Try and get the registers from the Usta. Note that this is a kind of last-ditch * thing and so no validation is done. */ private RegisterSet getRegistersFromUsta() throws IOException { log.fine("enter getRegistersFromUsta"); RegisterSet regs = tcb.getRegistersFromUsta(); if (registersValid(regs)) { log.finer("found good dsa in Usta"); return regs; } else { /* If there are more than three stack entries that's probably better than nothing */ boolean isDownStack = stackdirection == CEECAASTACK_DOWN; long dsaptr; if (isDownStack) { dsaptr = regs.getRegister(4); log.finer("p_dsaptr from reg 4 = " + hex(p_dsaptr)); } else { dsaptr = regs.getRegister(13); log.finer("p_dsaptr from reg 13 = " + hex(p_dsaptr)); } try { DsaStackFrame dsa = new DsaStackFrame(dsaptr, isDownStack, regs, space, Caa.this); int count = 0; for (; dsa != null; dsa = dsa.getParentFrame()) { if (++count > 3) { p_dsaptr = dsaptr; p_dsafmt = stackdirection; return regs; } } } catch (IOException e) { } catch (AssertionError e) { } } return null; } /** * Try and get the registers using the old svcdump code. This is for debugging * purposes only. Uses reflection so there is no compilation dependency. */ private void getRegistersFromSvcdump() { } /** * Validate the given DSA. Returns 0 if valid. Note because this is Java, we can't * modify the input parameters, so we use the instance variables instead and * val_dsa == p_dsaptr, val_dsafmt == p_dsafmt. */ private int validateDSA() { log.finer("attempt to validate " + hex(p_dsaptr) + " on " + (p_dsafmt == CEECAASTACK_DOWN ? "down" : "up") + " stack"); try { if (is64bit) { assert laa != 0; long l_sancptr = CeexlaaTemplate.getCeelaa_sanc64(inputStream, laa); assert l_sancptr != 0; long seghigh = CeexsancTemplate.getSanc_bos(inputStream, l_sancptr); long seglow = 0; long sanc_stack = CeexsancTemplate.getSanc_stack(inputStream, l_sancptr); long sanc_user_stack = CeexsancTemplate.getSanc_user_stack(inputStream, l_sancptr); if (sanc_stack == sanc_user_stack) { /* Get Stackfloor from sanc */ seglow = CeexsancTemplate.getSanc_user_floor(inputStream, l_sancptr); } else { /* Get StackFloor from LAA */ seglow = CeexlaaTemplate.getCeelaa_stackfloor64(inputStream, laa); } if (p_dsaptr < seghigh && (p_dsaptr + 0x800) >= seglow && (p_dsaptr & 0xf) == 0) { log.finer("dsa " + hex(p_dsaptr) + " is within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return 0; } else { log.finer("dsa " + hex(p_dsaptr) + " is NOT within seglow = " + hex(seglow) + " seghigh = " + hex(seghigh)); return ERROR; } } if (p_dsafmt == CEECAASTACK_DOWN) { /* the check for being in the current segment is commented out */ } else { if (is64bit) return ERROR; long tptr = ceecaaerrcm(); /* Chicken egg situation */ //assert !space.is64bit(); /* If the input DSA address is within the HCOM and double word aligned, * assume that it is good. */ if (p_dsaptr < (tptr + hcomLength) && p_dsaptr >= tptr && (p_dsaptr & 7) == 0) { log.finer("upstack dsa " + hex(p_dsaptr) + " is inside hcom"); return 0; } } long ddsa = ceecaaddsa(); long dsaptr = p_dsaptr; int dsafmt8 = p_dsafmt; long slowdsaptr = p_dsaptr; int slowdsafmt8 = p_dsafmt; for (boolean slow = false;; slow = !slow) { Ceexdsaf dsaf = new Ceexdsaf(space, dsaptr, dsafmt8, is64bit); /* If the stack direction is down but we are validating an upstack DSA * and the current DSA is inside the current segment of the down stack, * assume this must be a OS_NOSTACK call, return WARNING and replace * input DSA and DSAFmt with R4 value from this DSA */ log.finer("looping with dsa = " + hex(dsaptr)); if (stackdirection == CEECAASTACK_DOWN && p_dsafmt == CEECAASTACK_UP && dsaptr < seghigh && dsaptr >= seglow) { p_dsaptr = CeedsaTemplate.getCeedsar4(inputStream, dsaptr); p_dsafmt = CEECAASTACK_DOWN; log.finer("warning, try switching to down stack"); return WARNING; } long callers_dsaptr = dsaf.DSA_Prev; dsafmt8 = dsaf.DSA_Format; /* If we are not able to backchain any farther or we have encountered * a linkage stack, assume that the input DSA address is bad. */ if (callers_dsaptr == 0 || callers_dsaptr == F1SA) { log.finer("cannot backchain futher because " + (callers_dsaptr == 0 ? "zero" : "linkage stack") + " found"); return ERROR; } /* If we were able to backchain to the dummy DSA, the input DSA address * must be good. */ if (callers_dsaptr == ddsa) { log.finer("dummy dsa reached"); return 0; } /* If we backchained across a stack transition, assume that the input * DSA address is good. */ if (dsafmt8 != p_dsafmt) { log.finer("backchained across a stack transition"); return 0; } /* If we have located an upstack DSA with a valid NAB value, assume that * the input DSA address is good. */ if (dsafmt8 == CEECAASTACK_UP) { long tptr = CeedsaTemplate.getCeedsanab(inputStream, callers_dsaptr); if (tptr == dsaptr) { log.finer("upstack DSA is good"); return 0; } } dsaptr = callers_dsaptr; /* We use the Tortoise and the Hare algorithm to detect loops. If the slow * iterator is lapped it means there is a loop. */ if (slow) { dsaf = new Ceexdsaf(space, slowdsaptr, slowdsafmt8, is64bit); slowdsaptr = dsaf.DSA_Prev; slowdsafmt8 = dsaf.DSA_Format; } if (dsaptr == slowdsaptr) { log.finer("loop detected in DSA chain"); return ERROR; } } } catch (IOException e) { /* Any bad read means the DSA was invalid */ log.logp(Level.FINER,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Bad read", e); return ERROR; } catch (Exception e) { log.logp(Level.WARNING,"com.ibm.j9ddr.corereaders.tdump.zebedee.le.Caa.Cel4rreg", "validateDSA","Unexepected exception", e); throw new Error("Unexpected Exception:: " + e); } } } |
blob | blob, feature envy, long method | t | t | t | feature envy, long method | 0 | 14359 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/corereaders/tdump/zebedee/le/Caa.java/#L348-L800 | 1 | 2390 | 14359 | major | |
| 1919 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | data class | t | t | t | 0 | 12412 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 1919 | 12412 | major | ||
| 1951 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | data class, long method | t | t | f | data class | long method | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 1951 | 12534 | major |
| 276 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | long method, data class | t | t | t | data class | 0 | 2964 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 276 | 2964 | major | |
| 9 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected boolean validateToken(String token) { try { SignedJWT signed = SignedJWT.parse(token); boolean sigValid = validateSignature(signed); if (!sigValid) { LOGGER.warn("Signature of JWT token could not be verified. Please check the public key"); return false; } boolean expValid = validateExpiration(signed); if (!expValid) { LOGGER.warn("Expiration time validation of JWT token failed."); return false; } String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal(); if (currentUser == null) { return true; } String cookieUser = signed.getJWTClaimsSet().getSubject(); if (!cookieUser.equals(currentUser)) { return false; } return true; } catch (ParseException ex) { LOGGER.info("ParseException in validateToken", ex); return false; } } |
long method | long method | t | t | t | 0 | 612 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxJwtRealm.java/#L130-L156 | 1 | 9 | 612 | minor | ||
| 949 | { "message": "YES I found bad smells", "badSmells": [ "Blob", "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public void processElement(Object untypedElem) throws Exception { WindowedValue elem = (WindowedValue) untypedElem; Collection windows = windowFn.assignWindows( windowFn.new AssignContext() { @Override public T element() { return elem.getValue(); } @Override public Instant timestamp() { return elem.getTimestamp(); } @Override public BoundedWindow window() { return Iterables.getOnlyElement(elem.getWindows()); } }); WindowedValue res = WindowedValue.of(elem.getValue(), elem.getTimestamp(), windows, elem.getPane()); receiver.process(res); } |
feature envy | blob, feature envy, long method | t | t | t | blob, long method | 0 | 8517 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/AssignWindowsParDoFnFactory.java/#L93-L120 | 1 | 949 | 8517 | minor | |
| 1518 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11170 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 1518 | 11170 | minor | ||
| 1615 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 1615 | 11472 | minor | |
| 2177 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | 1. long method | t | t | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 2177 | 13408 | minor | ||
| 2607 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method | t | t | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 2607 | 15030 | minor | ||
| 1134 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JdbVariable implements Variable { private final LocalVariable jdiVariable; private final SimpleValue value; public JdbVariable(StackFrame jdiStackFrame, LocalVariable jdiVariable) { Value jdiValue = jdiStackFrame.getValue(jdiVariable); this.jdiVariable = jdiVariable; this.value = jdiValue == null ? new JdbNullValue() : new JdbValue(jdiValue, getVariablePath()); } public JdbVariable(SimpleValue value, LocalVariable jdiVariable) { this.jdiVariable = jdiVariable; this.value = value; } @Override public String getName() { return jdiVariable.name(); } @Override public boolean isPrimitive() { return JdbType.isPrimitive(jdiVariable.signature()); } @Override public SimpleValue getValue() { return value; } @Override public String getType() { return jdiVariable.typeName(); } @Override public VariablePath getVariablePath() { return new VariablePathImpl(getName()); } } |
data class | data class | t | t | t | 0 | 10054 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/model/JdbVariable.java/#L27-L67 | 1 | 1134 | 10054 | minor | ||
| 1685 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MultiDexConfig { private String name; public MultiDexConfig(String name) { this.name = name; } @Config(title = "Whether to enable fast", message = "Enable atlas , true/false", order = 0, group = "atlas") private boolean fastMultiDex = false; @Config(title = "The extra first dex class list", message = "The custom needs to be placed in the entry class in the first dex", order = 3, group = "atlas") private Set firstDexClasses = Sets.newHashSet(); /** * dex The number of subcontracting, 0 No restrictions, no two merges */ @Config(title = "dexThe number of", message = "0unlimited", order = 1, group = "atlas") private int dexCount; public int getMainDexListCount() { return mainDexListCount; } public void setMainDexListCount(int mainDexListCount) { this.mainDexListCount = mainDexListCount; } private int mainDexListCount; @Config(title = "dexSeparated rules", message = "a,b;c,d", order = 2, group = "atlas") private String dexSplitRules; @Config(title = "Does not enter the list of the first dex's blacklist", message = "a", order = 2, group = "atlas") private Set mainDexBlackList = Sets.newHashSet(); public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFastMultiDex() { return fastMultiDex; } public void setFastMultiDex(boolean fastMultiDex) { this.fastMultiDex = fastMultiDex; } public Set getMainDexBlackList() { return mainDexBlackList; } public void setMainDexBlackList(Set mainDexBlackList) { this.mainDexBlackList = mainDexBlackList; } public Set getFirstDexClasses() { return firstDexClasses; } public void setFirstDexClasses(Set firstDexClasses) { this.firstDexClasses = firstDexClasses; } public int getDexCount() { return dexCount; } public void setDexCount(int dexCount) { this.dexCount = dexCount; } public String getDexSplitRules() { return dexSplitRules; } public void setDexSplitRules(String dexSplitRules) { this.dexSplitRules = dexSplitRules; } } |
data class | Blob, Data Class | t | f | t | Blob | 0 | 11686 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/extension/MultiDexConfig.java/#L220-L302 | 1 | 1685 | 11686 | critical | |
| 1043 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | 1. long method | t | t | t | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 1043 | 9446 | major | ||
| 450 | {"output":"YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | 1. long method | t | t | f | long method | 0 | 4392 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 450 | 4392 | minor | |
| 2166 | Yes, I found bad smells(the bad smells are: 1. Long method 2. Data class 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method2 Data class3 Feature envy | t | f | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2166 | 13348 | critical | ||
| 2423 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | data class | t | t | t | 0 | 14441 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 2423 | 14441 | major | ||
| 456 | {"response": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
blob | blob | t | t | t | 0 | 4453 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 456 | 4453 | minor | ||
| 1885 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting and whitespace (inconsistent use of tabs/spaces) 4. Mixing of logging and exception handling in same method 5. Catching generic Exception class instead of specific exceptions 6. Use of instanceof operator 7. Nested, complex logic 8. Lack of proper error handling and messaging 9. Code duplication 10. Poor variable naming 11. Unnecessary use of Hashmap and casting 12. Unused variables 13. Inefficient use of EntityManager 14. Nested try-catch blocks 15. Inconsistent use of brackets/indentation 16. Fragile code (e.g. using string literals instead of constants) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method 2 Feature envy3 Inconsistent formatting and whitespace (inconsistent use of tabs/spaces)4 Mixing of logging and exception handling in same method5 Catching generic Exception class instead of specific exceptions6 Use of instanceof operator7 Nested, complex logic 8 Lack of proper error handling and messaging9 Code duplication | t | f | t | complex logic 8. Lack of proper error handling and messaging9. Code duplication | 0 | 12293 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 1885 | 12293 | minor | |
| 4359 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11504 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 2 | 4359 | 11504 | minor | ||
| 538 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LiteralKey { private Object value; private String type; private String lang; public LiteralKey(Object value, String type, String lang) { this.value = value; this.type = type != null ? type.intern() : null; this.lang = lang != null ? lang.intern() : null; } public String getLang() { return lang; } public String getType() { return type; } public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralKey that = (LiteralKey) o; if (lang != null ? !lang.equals(that.lang) : that.lang != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return value.equals(that.value); } @Override public int hashCode() { int result = value.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (lang != null ? lang.hashCode() : 0); return result; } } |
data class | 1. data class | t | t | f | data class | 0 | 5500 | https://github.com/apache/marmotta/blob/28c9b8b0791ea1693578af302981a1358e56933d/commons/marmotta-commons/src/main/java/org/apache/marmotta/commons/sesame/model/LiteralKey.java/#L25-L71 | 1 | 538 | 5500 | major | |
| 5396 | YES I have found bad smells the bad smells are:Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ILSMIndex createInstance(INCServiceContext serviceCtx) throws HyracksDataException { IIOManager ioManager = serviceCtx.getIoManager(); FileReference file = ioManager.resolve(path); List virtualBufferCaches = vbcProvider.getVirtualBufferCaches(serviceCtx, file); ioOpCallbackFactory.initialize(serviceCtx, this); return LSMRTreeUtils.createLSMTreeWithAntiMatterTuples(ioManager, virtualBufferCaches, file, storageManager.getBufferCache(serviceCtx), typeTraits, cmpFactories, btreeCmpFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, serviceCtx), opTrackerProvider.getOperationTracker(serviceCtx, this), ioSchedulerProvider.getIoScheduler(serviceCtx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR, metadataPageManagerFactory); } |
feature envy | Feature envy | t | f | t | 0 | 15166 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterLocalResource.java/#L96-L109 | 2 | 5396 | 15166 | minor | ||
| 1421 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10929 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1421 | 10929 | minor | |
| 762 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method, data class | t | t | t | data class | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 762 | 7113 | major | |
| 1262 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | long method | t | t | t | 0 | 10513 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1262 | 10513 | critical | ||
| 822 | {"output": "YES, I found bad smells\nthe bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _RepositorySoap_LabelItem implements ElementSerializable { // No attributes // Elements protected String workspaceName; protected String workspaceOwner; protected _VersionControlLabel label; protected _LabelItemSpec[] labelSpecs; protected _LabelChildOption children; public _RepositorySoap_LabelItem() { super(); } public _RepositorySoap_LabelItem( final String workspaceName, final String workspaceOwner, final _VersionControlLabel label, final _LabelItemSpec[] labelSpecs, final _LabelChildOption children) { // TODO : Call super() instead of setting all fields directly? setWorkspaceName(workspaceName); setWorkspaceOwner(workspaceOwner); setLabel(label); setLabelSpecs(labelSpecs); setChildren(children); } public String getWorkspaceName() { return this.workspaceName; } public void setWorkspaceName(String value) { this.workspaceName = value; } public String getWorkspaceOwner() { return this.workspaceOwner; } public void setWorkspaceOwner(String value) { this.workspaceOwner = value; } public _VersionControlLabel getLabel() { return this.label; } public void setLabel(_VersionControlLabel value) { this.label = value; } public _LabelItemSpec[] getLabelSpecs() { return this.labelSpecs; } public void setLabelSpecs(_LabelItemSpec[] value) { this.labelSpecs = value; } public _LabelChildOption getChildren() { return this.children; } public void setChildren(_LabelChildOption value) { if (value == null) { throw new IllegalArgumentException("'children' is a required element, its value cannot be null"); } this.children = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "workspaceName", this.workspaceName); XMLStreamWriterHelper.writeElement( writer, "workspaceOwner", this.workspaceOwner); if (this.label != null) { this.label.writeAsElement( writer, "label"); } if (this.labelSpecs != null) { /* * The element type is an array. */ writer.writeStartElement("labelSpecs"); for (int iterator0 = 0; iterator0 < this.labelSpecs.length; iterator0++) { this.labelSpecs[iterator0].writeAsElement( writer, "LabelItemSpec"); } writer.writeEndElement(); } this.children.writeAsElement( writer, "children"); writer.writeEndElement(); } } |
data class | 1. data class | t | t | t | 0 | 7701 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/versioncontrol/clientservices/_03/_RepositorySoap_LabelItem.java/#L42-L176 | 1 | 822 | 7701 | major | ||
| 425 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toCommandLine() { return preparer.map(it -> it.apply(value)).orElseGet(() -> value.toString()); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 4257 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/build/CommandLine.java/#L245-L247 | 1 | 425 | 4257 | minor |
| 4398 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 11629 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 4398 | 11629 | minor | |
| 1887 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12299 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 1887 | 12299 | minor | ||
| 234 | {"output": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicUUID implements UUID, Formatable { /* ** Fields of BasicUUID */ private long majorId; // only using 48 bits private long timemillis; private int sequence; /* ** Methods of BasicUUID */ /** Constructor only called by BasicUUIDFactory. **/ public BasicUUID(long majorId, long timemillis, int sequence) { this.majorId = majorId; this.timemillis = timemillis; this.sequence = sequence; } /** Constructor only called by BasicUUIDFactory. Constructs a UUID from the string representation produced by toString. @see BasicUUID#toString **/ public BasicUUID(String uuidstring) { StringReader sr = new StringReader(uuidstring); sequence = (int) readMSB(sr); long ltimemillis = readMSB(sr) << 32; ltimemillis += readMSB(sr) << 16; ltimemillis += readMSB(sr); timemillis = ltimemillis; majorId = readMSB(sr); } /* * Formatable methods */ // no-arg constructor, required by Formatable public BasicUUID() { super(); } /** Write this out. @exception IOException error writing to log stream */ public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(majorId); out.writeLong(timemillis); out.writeInt(sequence); } /** Read this in @exception IOException error reading from log stream */ public void readExternal(ObjectInput in) throws IOException { majorId = in.readLong(); timemillis = in.readLong(); sequence = in.readInt(); } /** Return my format identifier. */ public int getTypeFormatId() { return StoredFormatIds.BASIC_UUID; } private static void writeMSB(char[] data, int offset, long value, int nbytes) { for (int i = nbytes - 1; i >= 0; i--) { long b = (value & (255L << (8 * i))) >>> (8 * i); int c = (int) ((b & 0xf0) >> 4); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); c = (int) (b & 0x0f); data[offset++] = (char) (c < 10 ? c + '0' : (c - 10) + 'a'); } } /** Read a long value, msb first, from its character representation in the string reader, using '-' or end of string to delimit. **/ private static long readMSB(StringReader sr) { long value = 0; try { int c; while ((c = sr.read()) != -1) { if (c == '-') break; value <<= 4; int nibble; if (c <= '9') nibble = c - '0'; else if (c <= 'F') nibble = c - 'A' + 10; else nibble = c - 'a' + 10; value += nibble; } } catch (Exception e) { } return value; } /* ** Methods of UUID */ /** Implement value equality. **/ public boolean equals(Object otherObject) { if (!(otherObject instanceof BasicUUID)) return false; BasicUUID other = (BasicUUID) otherObject; return (this.sequence == other.sequence) && (this.timemillis == other.timemillis) && (this.majorId == other.majorId); } /** Provide a hashCode which is compatible with the equals() method. **/ public int hashCode() { long hc = majorId ^ timemillis; return sequence ^ ((int) (hc >> 4)); } /** Produce a string representation of this UUID which can be passed to UUIDFactory.recreateUUID later on to reconstruct it. The funny representation is designed to (sort of) match the format of Microsoft's UUIDGEN utility. */ public String toString() {return stringWorkhorse( '-' );} /** Produce a string representation of this UUID which is suitable for use as a unique ANSI identifier. */ public String toANSIidentifier() {return "U" + stringWorkhorse( 'X' );} /** * Private workhorse of the string making routines. * * @param separator Character to separate number blocks. * Null means do not include a separator. * * @return string representation of UUID. */ public String stringWorkhorse( char separator ) { char[] data = new char[36]; writeMSB(data, 0, (long) sequence, 4); int offset = 8; if (separator != 0) data[offset++] = separator; long ltimemillis = timemillis; writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2); offset += 4; if (separator != 0) data[offset++] = separator; writeMSB(data, offset, majorId, 6); offset += 12; return new String(data, 0, offset); } /** Clone this UUID. @return a copy of this UUID */ public UUID cloneMe() { return new BasicUUID(majorId, timemillis, sequence); } } |
blob | blob, long method | t | t | t | long method | 0 | 2553 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/services/uuid/BasicUUID.java/#L36-L250 | 1 | 234 | 2553 | minor | |
| 2347 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | t | long method | 0 | 14196 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 2347 | 14196 | major | |
| 743 | { "output": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 743 | 6978 | major | |
| 794 | {"message":"YES I found bad smells","bad smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** Default object name used for binding: "target". */ public static final String DEFAULT_OBJECT_NAME = "target"; /** Default limit for array and collection growing: 256. */ public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT = 256; /** * We'll create a lot of DataBinder instances: Let's use a static logger. */ protected static final Log logger = LogFactory.getLog(DataBinder.class); @Nullable private final Object target; private final String objectName; @Nullable private AbstractPropertyBindingResult bindingResult; @Nullable private SimpleTypeConverter typeConverter; private boolean ignoreUnknownFields = true; private boolean ignoreInvalidFields = false; private boolean autoGrowNestedPaths = true; private int autoGrowCollectionLimit = DEFAULT_AUTO_GROW_COLLECTION_LIMIT; @Nullable private String[] allowedFields; @Nullable private String[] disallowedFields; @Nullable private String[] requiredFields; @Nullable private ConversionService conversionService; @Nullable private MessageCodesResolver messageCodesResolver; private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); private final List validators = new ArrayList<>(); /** * Create a new DataBinder instance, with default object name. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @see #DEFAULT_OBJECT_NAME */ public DataBinder(@Nullable Object target) { this(target, DEFAULT_OBJECT_NAME); } /** * Create a new DataBinder instance. * @param target the target object to bind onto (or {@code null} * if the binder is just used to convert a plain parameter value) * @param objectName the name of the target object */ public DataBinder(@Nullable Object target, String objectName) { this.target = ObjectUtils.unwrapOptional(target); this.objectName = objectName; } /** * Return the wrapped target object. */ @Nullable public Object getTarget() { return this.target; } /** * Return the name of the bound object. */ public String getObjectName() { return this.objectName; } /** * Set whether this binder should attempt to "auto-grow" a nested path that contains a null value. * If "true", a null path location will be populated with a default object value and traversed * instead of resulting in an exception. This flag also enables auto-growth of collection elements * when accessing an out-of-bounds index. * Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported * for bean property access (DataBinder's default mode) and field access. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowNestedPaths */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowNestedPaths before other configuration methods"); this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify the limit for array and collection auto-growing. * Default is 256, preventing OutOfMemoryErrors in case of large indexes. * Raise this limit if your auto-growing needs are unusually high. * @see #initBeanPropertyAccess() * @see org.springframework.beans.BeanWrapper#setAutoGrowCollectionLimit */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call setAutoGrowCollectionLimit before other configuration methods"); this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the current limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Initialize standard JavaBean property access for this DataBinder. * This is the default; an explicit call just leads to eager initialization. * @see #initDirectFieldAccess() * @see #createBeanPropertyBindingResult() */ public void initBeanPropertyAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initBeanPropertyAccess before other configuration methods"); this.bindingResult = createBeanPropertyBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using standard * JavaBean property access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createBeanPropertyBindingResult() { BeanPropertyBindingResult result = new BeanPropertyBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths(), getAutoGrowCollectionLimit()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Initialize direct field access for this DataBinder, * as alternative to the default bean property access. * @see #initBeanPropertyAccess() * @see #createDirectFieldBindingResult() */ public void initDirectFieldAccess() { Assert.state(this.bindingResult == null, "DataBinder is already initialized - call initDirectFieldAccess before other configuration methods"); this.bindingResult = createDirectFieldBindingResult(); } /** * Create the {@link AbstractPropertyBindingResult} instance using direct * field access. * @since 4.2.1 */ protected AbstractPropertyBindingResult createDirectFieldBindingResult() { DirectFieldBindingResult result = new DirectFieldBindingResult(getTarget(), getObjectName(), isAutoGrowNestedPaths()); if (this.conversionService != null) { result.initConversion(this.conversionService); } if (this.messageCodesResolver != null) { result.setMessageCodesResolver(this.messageCodesResolver); } return result; } /** * Return the internal BindingResult held by this DataBinder, * as an AbstractPropertyBindingResult. */ protected AbstractPropertyBindingResult getInternalBindingResult() { if (this.bindingResult == null) { initBeanPropertyAccess(); } return this.bindingResult; } /** * Return the underlying PropertyAccessor of this binder's BindingResult. */ protected ConfigurablePropertyAccessor getPropertyAccessor() { return getInternalBindingResult().getPropertyAccessor(); } /** * Return this binder's underlying SimpleTypeConverter. */ protected SimpleTypeConverter getSimpleTypeConverter() { if (this.typeConverter == null) { this.typeConverter = new SimpleTypeConverter(); if (this.conversionService != null) { this.typeConverter.setConversionService(this.conversionService); } } return this.typeConverter; } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected PropertyEditorRegistry getPropertyEditorRegistry() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the underlying TypeConverter of this binder's BindingResult. */ protected TypeConverter getTypeConverter() { if (getTarget() != null) { return getInternalBindingResult().getPropertyAccessor(); } else { return getSimpleTypeConverter(); } } /** * Return the BindingResult instance created by this DataBinder. * This allows for convenient access to the binding results after * a bind operation. * @return the BindingResult instance, to be treated as BindingResult * or as Errors instance (Errors is a super-interface of BindingResult) * @see Errors * @see #bind */ public BindingResult getBindingResult() { return getInternalBindingResult(); } /** * Set whether to ignore unknown fields, that is, whether to ignore bind * parameters that do not have corresponding fields in the target object. * Default is "true". Turn this off to enforce that all bind parameters * must have a matching field in the target object. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { this.ignoreUnknownFields = ignoreUnknownFields; } /** * Return whether to ignore unknown fields when binding. */ public boolean isIgnoreUnknownFields() { return this.ignoreUnknownFields; } /** * Set whether to ignore invalid fields, that is, whether to ignore bind * parameters that have corresponding fields in the target object which are * not accessible (for example because of null values in the nested path). * Default is "false". Turn this on to ignore bind parameters for * nested objects in non-existing parts of the target object graph. * Note that this setting only applies to binding operations * on this DataBinder, not to retrieving values via its * {@link #getBindingResult() BindingResult}. * @see #bind */ public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { this.ignoreInvalidFields = ignoreInvalidFields; } /** * Return whether to ignore invalid fields when binding. */ public boolean isIgnoreInvalidFields() { return this.ignoreInvalidFields; } /** * Register fields that should be allowed for binding. Default is all * fields. Restrict this for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of disallowed fields. * @param allowedFields array of field names * @see #setDisallowedFields * @see #isAllowed(String) */ public void setAllowedFields(@Nullable String... allowedFields) { this.allowedFields = PropertyAccessorUtils.canonicalPropertyNames(allowedFields); } /** * Return the fields that should be allowed for binding. * @return array of field names */ @Nullable public String[] getAllowedFields() { return this.allowedFields; } /** * Register fields that should not be allowed for binding. Default is none. * Mark fields as disallowed for example to avoid unwanted modifications * by malicious users when binding HTTP request parameters. * Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching * can be implemented by overriding the {@code isAllowed} method. * Alternatively, specify a list of allowed fields. * @param disallowedFields array of field names * @see #setAllowedFields * @see #isAllowed(String) */ public void setDisallowedFields(@Nullable String... disallowedFields) { this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields); } /** * Return the fields that should not be allowed for binding. * @return array of field names */ @Nullable public String[] getDisallowedFields() { return this.disallowedFields; } /** * Register fields that are required for each binding process. * If one of the specified fields is not contained in the list of * incoming property values, a corresponding "missing field" error * will be created, with error code "required" (by the default * binding error processor). * @param requiredFields array of field names * @see #setBindingErrorProcessor * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE */ public void setRequiredFields(@Nullable String... requiredFields) { this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields); if (logger.isDebugEnabled()) { logger.debug("DataBinder requires binding of required fields [" + StringUtils.arrayToCommaDelimitedString(requiredFields) + "]"); } } /** * Return the fields that are required for each binding process. * @return array of field names */ @Nullable public String[] getRequiredFields() { return this.requiredFields; } /** * Set the strategy to use for resolving errors into message codes. * Applies the given strategy to the underlying errors holder. * Default is a DefaultMessageCodesResolver. * @see BeanPropertyBindingResult#setMessageCodesResolver * @see DefaultMessageCodesResolver */ public void setMessageCodesResolver(@Nullable MessageCodesResolver messageCodesResolver) { Assert.state(this.messageCodesResolver == null, "DataBinder is already initialized with MessageCodesResolver"); this.messageCodesResolver = messageCodesResolver; if (this.bindingResult != null && messageCodesResolver != null) { this.bindingResult.setMessageCodesResolver(messageCodesResolver); } } /** * Set the strategy to use for processing binding errors, that is, * required field errors and {@code PropertyAccessException}s. * Default is a DefaultBindingErrorProcessor. * @see DefaultBindingErrorProcessor */ public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) { Assert.notNull(bindingErrorProcessor, "BindingErrorProcessor must not be null"); this.bindingErrorProcessor = bindingErrorProcessor; } /** * Return the strategy for processing binding errors. */ public BindingErrorProcessor getBindingErrorProcessor() { return this.bindingErrorProcessor; } /** * Set the Validator to apply after each binding step. * @see #addValidators(Validator...) * @see #replaceValidators(Validator...) */ public void setValidator(@Nullable Validator validator) { assertValidators(validator); this.validators.clear(); if (validator != null) { this.validators.add(validator); } } private void assertValidators(Validator... validators) { Object target = getTarget(); for (Validator validator : validators) { if (validator != null && (target != null && !validator.supports(target.getClass()))) { throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + target); } } } /** * Add Validators to apply after each binding step. * @see #setValidator(Validator) * @see #replaceValidators(Validator...) */ public void addValidators(Validator... validators) { assertValidators(validators); this.validators.addAll(Arrays.asList(validators)); } /** * Replace the Validators to apply after each binding step. * @see #setValidator(Validator) * @see #addValidators(Validator...) */ public void replaceValidators(Validator... validators) { assertValidators(validators); this.validators.clear(); this.validators.addAll(Arrays.asList(validators)); } /** * Return the primary Validator to apply after each binding step, if any. */ @Nullable public Validator getValidator() { return (!this.validators.isEmpty() ? this.validators.get(0) : null); } /** * Return the Validators to apply after data binding. */ public List getValidators() { return Collections.unmodifiableList(this.validators); } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface //--------------------------------------------------------------------- /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(@Nullable ConversionService conversionService) { Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService"); this.conversionService = conversionService; if (this.bindingResult != null && conversionService != null) { this.bindingResult.initConversion(conversionService); } } /** * Return the associated ConversionService, if any. */ @Nullable public ConversionService getConversionService() { return this.conversionService; } /** * Add a custom formatter, applying it to all fields matching the * {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } /** * Add a custom formatter for the field type specified in {@link Formatter} class, * applying it to the specified fields only, if any, or otherwise to all fields. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add, generically declared for a specific type * @param fields the fields to apply the formatter to, or none if to be applied to all * @since 4.2 * @see #registerCustomEditor(Class, String, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, String... fields) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); Class fieldType = adapter.getFieldType(); if (ObjectUtils.isEmpty(fields)) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } else { for (String field : fields) { getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter); } } } /** * Add a custom formatter, applying it to the specified field types only, if any, * or otherwise to all fields matching the {@link Formatter}-declared type. * Registers a corresponding {@link PropertyEditor} adapter underneath the covers. * @param formatter the formatter to add (does not need to generically declare a * field type if field types are explicitly specified as parameters) * @param fieldTypes the field types to apply the formatter to, or none if to be * derived from the given {@link Formatter} implementation class * @since 4.2 * @see #registerCustomEditor(Class, PropertyEditor) */ public void addCustomFormatter(Formatter formatter, Class... fieldTypes) { FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter); if (ObjectUtils.isEmpty(fieldTypes)) { getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter); } else { for (Class fieldType : fieldTypes) { getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter); } } } @Override public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } @Override public void registerCustomEditor(@Nullable Class requiredType, @Nullable String field, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, field, propertyEditor); } @Override @Nullable public PropertyEditor findCustomEditor(@Nullable Class requiredType, @Nullable String propertyPath) { return getPropertyEditorRegistry().findCustomEditor(requiredType, propertyPath); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable MethodParameter methodParam) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, methodParam); } @Override @Nullable public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable Field field) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, field); } @Nullable @Override public T convertIfNecessary(@Nullable Object value, @Nullable Class requiredType, @Nullable TypeDescriptor typeDescriptor) throws TypeMismatchException { return getTypeConverter().convertIfNecessary(value, requiredType, typeDescriptor); } /** * Bind the given property values to this binder's target. * This call can create field errors, representing basic binding * errors like a required field (code "required"), or type mismatch * between value and bean property (code "typeMismatch"). * Note that the given PropertyValues should be a throwaway instance: * For efficiency, it will be modified to just contain allowed fields if it * implements the MutablePropertyValues interface; else, an internal mutable * copy will be created for this purpose. Pass in a copy of the PropertyValues * if you want your original instance to stay unmodified in any case. * @param pvs property values to bind * @see #doBind(org.springframework.beans.MutablePropertyValues) */ public void bind(PropertyValues pvs) { MutablePropertyValues mpvs = (pvs instanceof MutablePropertyValues ? (MutablePropertyValues) pvs : new MutablePropertyValues(pvs)); doBind(mpvs); } /** * Actual implementation of the binding process, working with the * passed-in MutablePropertyValues instance. * @param mpvs the property values to bind, * as MutablePropertyValues instance * @see #checkAllowedFields * @see #checkRequiredFields * @see #applyPropertyValues */ protected void doBind(MutablePropertyValues mpvs) { checkAllowedFields(mpvs); checkRequiredFields(mpvs); applyPropertyValues(mpvs); } /** * Check the given property values against the allowed fields, * removing values for fields that are not allowed. * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug("Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } } /** * Return if the given field is allowed for binding. * Invoked for each passed-in property value. * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, * as well as direct equality, in the specified lists of allowed fields and * disallowed fields. A field matching a disallowed pattern will not be accepted * even if it also happens to match a pattern in the allowed list. * Can be overridden in subclasses. * @param field the field to check * @return if the field is allowed * @see #setAllowedFields * @see #setDisallowedFields * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean isAllowed(String field) { String[] allowed = getAllowedFields(); String[] disallowed = getDisallowedFields(); return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) && (ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field))); } /** * Check the given property values against the required fields, * generating missing field errors where appropriate. * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { Map propertyValues = new HashMap<>(); PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } for (String field : requiredFields) { PropertyValue pv = propertyValues.get(field); boolean empty = (pv == null || pv.getValue() == null); if (!empty) { if (pv.getValue() instanceof String) { empty = !StringUtils.hasText((String) pv.getValue()); } else if (pv.getValue() instanceof String[]) { String[] values = (String[]) pv.getValue(); empty = (values.length == 0 || !StringUtils.hasText(values[0])); } } if (empty) { // Use bind error processor to create FieldError. getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult()); // Remove property from property values to bind: // It has already caused a field error with a rejected value. if (pv != null) { mpvs.removePropertyValue(pv); propertyValues.remove(field); } } } } } /** * Apply given property values to the target object. * Default implementation applies all of the supplied property * values as bean property values. By default, unknown fields will * be ignored. * @param mpvs the property values to be bound (can be modified) * @see #getTarget * @see #getPropertyAccessor * @see #isIgnoreUnknownFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processPropertyAccessException */ protected void applyPropertyValues(MutablePropertyValues mpvs) { try { // Bind request parameters onto target object. getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields()); } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } /** * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { validator.validate(target, bindingResult); } } /** * Invoke the specified Validators, if any, with the given validation hints. * Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @since 3.1 * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { Object target = getTarget(); Assert.state(target != null, "No target to validate"); BindingResult bindingResult = getBindingResult(); // Call each validator with the same binding result for (Validator validator : getValidators()) { if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { ((SmartValidator) validator).validate(target, bindingResult, validationHints); } else if (validator != null) { validator.validate(target, bindingResult); } } } /** * Close this DataBinder, which may result in throwing * a BindException if it encountered any errors. * @return the model Map, containing target object and Errors instance * @throws BindException if there were any errors in the bind operation * @see BindingResult#getModel() */ public Map close() throws BindException { if (getBindingResult().hasErrors()) { throw new BindException(getBindingResult()); } return getBindingResult().getModel(); } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 7554 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-context/src/main/java/org/springframework/validation/DataBinder.java/#L110-L911 | 1 | 794 | 7554 | minor |
| 2422 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Feature envy2 Long method | t | f | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2422 | 14435 | minor | ||
| 767 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 7227 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 767 | 7227 | major | |
| 798 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RowReadSupport extends ReadSupport { private TypeInformation returnTypeInfo; @Override public ReadContext init(InitContext initContext) { checkNotNull(initContext, "initContext"); returnTypeInfo = ParquetSchemaConverter.fromParquetType(initContext.getFileSchema()); return new ReadContext(initContext.getFileSchema()); } @Override public RecordMaterializer prepareForRead( Configuration configuration, Map keyValueMetaData, MessageType fileSchema, ReadContext readContext) { return new RowMaterializer(readContext.getRequestedSchema(), returnTypeInfo); } } |
data class | data class, long method | t | t | t | long method | 0 | 7569 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/RowReadSupport.java/#L37-L54 | 1 | 798 | 7569 | minor | |
| 304 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | blob, data class | t | t | t | blob | 0 | 3183 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 1 | 304 | 3183 | major | |
| 1781 | YES I found bad smells the bad smells are: Long method, Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method, Feature envy | t | f | t | Feature envy. | 0 | 11962 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 1781 | 11962 | minor | |
| 111 | { "message": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 1461 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 111 | 1461 | major | ||
| 2271 | { "output": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class BaseObject { /** Type identifier of the object */ public String type; /** * Constructs an empty object */ public BaseObject() { type = this.getClass().getCanonicalName(); } /** * Constructs object with a given type * @param type the type identifier */ public BaseObject(String type) { this.type = type; } /** * Get type of this object. * @return type of the object */ public String getType() { return type; } } |
data class | data class | t | t | t | 0 | 13766 | https://github.com/spring-projects/spring-hadoop/blob/cda92b8ab6b5e8a8defe8ae5822e966e0a9d34eb/spring-yarn/spring-yarn-integration/src/main/java/org/springframework/yarn/integration/ip/mind/binding/BaseObject.java/#L24-L52 | 1 | 2271 | 13766 | minor | ||
| 2640 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Message chain 5. Unnecessary conditional logic 6. Inconsistent variable naming conventions 7. Use of system exceptions 8. Inappropriate handling of errors or exceptions 9. Mixing of business logic and error handling code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Duplicate code3 Feature envy4 Message chain5 Unnecessary conditional logic6 Inconsistent variable naming conventions7 Use of system exceptions8 Inappropriate handling of errors or exceptions9 Mixing of business logic and error handling code | t | f | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2640 | 15143 | major | ||
| 1130 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | long method, data class | t | t | t | long method | 0 | 10018 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1130 | 10018 | minor | |
| 2379 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "the bad smells are": [ "Data Class" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SparkVersion { private static final Logger logger = LoggerFactory.getLogger(SparkVersion.class); public static final SparkVersion SPARK_1_6_0 = SparkVersion.fromVersionString("1.6.0"); public static final SparkVersion SPARK_2_0_0 = SparkVersion.fromVersionString("2.0.0"); public static final SparkVersion SPARK_2_3_0 = SparkVersion.fromVersionString("2.3.0"); public static final SparkVersion SPARK_2_3_1 = SparkVersion.fromVersionString("2.3.1"); public static final SparkVersion SPARK_2_4_0 = SparkVersion.fromVersionString("2.4.0"); public static final SparkVersion SPARK_3_0_0 = SparkVersion.fromVersionString("3.0.0"); public static final SparkVersion MIN_SUPPORTED_VERSION = SPARK_1_6_0; public static final SparkVersion UNSUPPORTED_FUTURE_VERSION = SPARK_3_0_0; private int version; private int majorVersion; private int minorVersion; private int patchVersion; private String versionString; SparkVersion(String versionString) { this.versionString = versionString; try { int pos = versionString.indexOf('-'); String numberPart = versionString; if (pos > 0) { numberPart = versionString.substring(0, pos); } String versions[] = numberPart.split("\\."); this.majorVersion = Integer.parseInt(versions[0]); this.minorVersion = Integer.parseInt(versions[1]); this.patchVersion = Integer.parseInt(versions[2]); // version is always 5 digits. (e.g. 2.0.0 -> 20000, 1.6.2 -> 10602) version = Integer.parseInt(String.format("%d%02d%02d", majorVersion, minorVersion, patchVersion)); } catch (Exception e) { logger.error("Can not recognize Spark version " + versionString + ". Assume it's a future release", e); // assume it is future release version = 99999; } } public int toNumber() { return version; } public String toString() { return versionString; } public boolean isUnsupportedVersion() { return olderThan(MIN_SUPPORTED_VERSION) || newerThanEquals(UNSUPPORTED_FUTURE_VERSION); } public static SparkVersion fromVersionString(String versionString) { return new SparkVersion(versionString); } public boolean isSpark2() { return this.newerThanEquals(SPARK_2_0_0); } public boolean isSecretSocketSupported() { return this.newerThanEquals(SparkVersion.SPARK_2_4_0) || this.newerThanEqualsPatchVersion(SPARK_2_3_1) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.2.2")) || this.newerThanEqualsPatchVersion(SparkVersion.fromVersionString("2.1.3")); } public boolean equals(Object versionToCompare) { return version == ((SparkVersion) versionToCompare).version; } public boolean newerThan(SparkVersion versionToCompare) { return version > versionToCompare.version; } public boolean newerThanEquals(SparkVersion versionToCompare) { return version >= versionToCompare.version; } public boolean newerThanEqualsPatchVersion(SparkVersion versionToCompare) { return majorVersion == versionToCompare.majorVersion && minorVersion == versionToCompare.minorVersion && patchVersion >= versionToCompare.patchVersion; } public boolean olderThan(SparkVersion versionToCompare) { return version < versionToCompare.version; } public boolean olderThanEquals(SparkVersion versionToCompare) { return version <= versionToCompare.version; } } |
data class | the bad smells are: data class | t | t | t | 0 | 14336 | https://github.com/apache/zeppelin/blob/4219d552349f8f7f3e6de34505b8a8ae9835f98b/spark/interpreter/src/main/java/org/apache/zeppelin/spark/SparkVersion.java/#L25-L123 | 1 | 2379 | 14336 | minor | ||
| 527 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private QueryBuilder convertCustomFlagCriterion(SearchQuery.CustomFlagCriterion criterion) { QueryBuilder termQueryBuilder = termQuery(JsonMessageConstants.USER_FLAGS, criterion.getFlag()); if (criterion.getOperator().isSet()) { return termQueryBuilder; } else { return boolQuery().mustNot(termQueryBuilder); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5449 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/elasticsearch/src/main/java/org/apache/james/mailbox/elasticsearch/query/CriterionConverter.java/#L132-L139 | 2 | 527 | 5449 | minor | ||
| 1497 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | long method | t | t | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 1 | 1497 | 11126 | minor | ||
| 254 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2738 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 254 | 2738 | critical | |
| 2404 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 2404 | 14385 | major | ||
| 2530 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 2 | 2530 | 14736 | minor | |
| 2055 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | long method | t | t | t | 0 | 12939 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 1 | 2055 | 12939 | major | ||
| 1017 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitBranchJson { private final static String REFS_HEADS = "refs/heads/"; //$NON-NLS-1$ private final String objectId; private final String fullName; @JsonCreator public TfsGitBranchJson( @JsonProperty("objectId") final String objectId, @JsonProperty("name") final String fullName) { this.objectId = objectId; this.fullName = fullName; } public String getObjectId() { return objectId; } public String getName() { if (fullName.startsWith(REFS_HEADS)) { return fullName.substring(REFS_HEADS.length()); } else { return fullName; } } public String getFullName() { return fullName; } } |
data class | long method, data class | t | t | t | long method | 0 | 9315 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitBranchJson.java/#L9-L39 | 1 | 1017 | 9315 | minor | |
| 1305 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 1 | 1305 | 10673 | minor | |
| 396 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | data class, long method | t | t | t | long method | 0 | 4035 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 1 | 396 | 4035 | major | |
| 1561 | YES I found bad smells the bad smells are: 1. Long method 2. Inconsistent indentation 3. Empty catch statement 4. Magic numbers 5. Use of switch statement 6. Use of multiple if/else statements 7. Use of null check syntax 8. Code duplication/repetition 9. Poor variable naming 10. Mixing of logic and data manipulation 11. Unnecessary commenting 12. Nested conditionals 13. Hard-coded values 14. Mix of different coding styles/mixing of languages (Java and protocols) 15. Use of bitwise operations (bitField0_) 16. Lack of proper error handling/reporting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(this.getUnknownFields()); while (true) { int tag = 0; try { tag = input.readTag(); } catch (Exception e) { // do nothing } switch (tag) { case 0 : this.setUnknownFields(unknownFields.build()); onChanged(); return this; default : { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10 : { bitField0_ |= 0x00000001; message_ = input.readBytes(); break; } case 16 : { int rawValue = input.readEnum(); org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType value = org.eclipse.orion.server.cf.loggregator.LoggregatorMessage.Message.MessageType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; messageType_ = value; } break; } case 24 : { bitField0_ |= 0x00000004; timestamp_ = input.readSInt64(); break; } case 34 : { bitField0_ |= 0x00000008; appId_ = input.readBytes(); break; } case 50 : { bitField0_ |= 0x00000010; sourceId_ = input.readBytes(); break; } case 58 : { ensureDrainUrlsIsMutable(); drainUrls_.add(input.readBytes()); break; } case 66 : { bitField0_ |= 0x00000040; sourceName_ = input.readBytes(); break; } } } } |
long method | Long method2 Inconsistent indentation3 Empty catch statement4 Magic numbers5 Use of switch statement6 Use of multiple if/else statements7 Use of null check syntax8 Code duplication/repetition9 Poor variable naming | t | f | t | 0 | 11308 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.cf/src/org/eclipse/orion/server/cf/loggregator/LoggregatorMessage.java/#L651-L716 | 2 | 1561 | 11308 | major | ||
| 605 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Magic numbers 5. Poor naming conventions for variables and methods 6. Nested conditional statements 7. Lack of comments or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Duplicate code3 Feature envy4 Magic numbers5 Poor naming conventions for variables and methods6 Nested conditional statements7 Lack of comments or documentation | t | f | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 605 | 6050 | minor | ||
| 1972 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: List freevarDefs(int pos, List freevars, Symbol owner, long additionalFlags) { long flags = FINAL | SYNTHETIC | additionalFlags; List defs = List.nil(); Set proxyNames = new HashSet<>(); for (List l = freevars; l.nonEmpty(); l = l.tail) { VarSymbol v = l.head; int index = 0; Name proxyName; do { proxyName = proxyName(v.name, index++); } while (!proxyNames.add(proxyName)); VarSymbol proxy = new VarSymbol( flags, proxyName, v.erasure(types), owner); proxies.put(v, proxy); JCVariableDecl vd = make.at(pos).VarDef(proxy, null); vd.vartype = access(vd.vartype); defs = defs.prepend(vd); } return defs; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12611 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Lower.java/#L1457-L1477 | 2 | 1972 | 12611 | minor | ||
| 1207 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10290 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 1207 | 10290 | major | ||
| 2574 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14912 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2574 | 14912 | minor | ||
| 1637 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long Method, Blob | t | f | t | Blob | 0 | 11527 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 1637 | 11527 | minor | |
| 1231 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ErrorDataException extends Exception { /** serialVersionUID. */ private static final long serialVersionUID = -9052741930614009382L; /** The rpc data package. */ private RpcDataPackage rpcDataPackage; /** The error code. */ private int errorCode; /** * Gets the error code. * * @return the error code */ public int getErrorCode() { return errorCode; } /** * Sets the error code. * * @param errorCode the new error code */ public void setErrorCode(int errorCode) { this.errorCode = errorCode; } /** * Gets the rpc data package. * * @return the rpc data package */ public RpcDataPackage getRpcDataPackage() { return rpcDataPackage; } /** * Sets the rpc data package. * * @param rpcDataPackage the new rpc data package */ public void setRpcDataPackage(RpcDataPackage rpcDataPackage) { this.rpcDataPackage = rpcDataPackage; } /** * Instantiates a new error data exception. */ public ErrorDataException() { super(); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause */ public ErrorDataException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new error data exception. * * @param message the message * @param cause the cause * @param errorCode the error code */ public ErrorDataException(String message, Throwable cause, int errorCode) { super(message, cause); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param message the message */ public ErrorDataException(String message) { super(message); } /** * Instantiates a new error data exception. * * @param message the message * @param errorCode the error code */ public ErrorDataException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * Instantiates a new error data exception. * * @param cause the cause */ public ErrorDataException(Throwable cause) { super(cause); } /** * Instantiates a new error data exception. * * @param cause the cause * @param errorCode the error code */ public ErrorDataException(Throwable cause, int errorCode) { super(cause); this.errorCode = errorCode; } } |
data class | data class | t | t | t | 0 | 10364 | https://github.com/baidu/Jprotobuf-rpc-socket/blob/4422e24c725eaf1f76646f674718bcc8750a4e1d/jprotobuf-rpc-core/src/main/java/com/baidu/jprotobuf/pbrpc/ErrorDataException.java/#L28-L145 | 1 | 1231 | 10364 | critical | ||
| 585 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("rawtypes") public interface FlowableRxInvoker extends RxInvoker { @Override Flowable get(); @Override Flowable get(Class responseType); @Override Flowable get(GenericType responseType); @Override Flowable put(Entity entity); @Override Flowable put(Entity entity, Class clazz); @Override Flowable put(Entity entity, GenericType type); @Override Flowable post(Entity entity); @Override Flowable post(Entity entity, Class clazz); @Override Flowable post(Entity entity, GenericType type); @Override Flowable delete(); @Override Flowable delete(Class responseType); @Override Flowable delete(GenericType responseType); @Override Flowable head(); @Override Flowable options(); @Override Flowable options(Class responseType); @Override Flowable options(GenericType responseType); @Override Flowable trace(); @Override Flowable trace(Class responseType); @Override Flowable trace(GenericType responseType); @Override Flowable method(String name); @Override Flowable method(String name, Class responseType); @Override Flowable method(String name, GenericType responseType); @Override Flowable method(String name, Entity entity); @Override Flowable method(String name, Entity entity, Class responseType); @Override Flowable method(String name, Entity entity, GenericType responseType); } |
data class | long method, data class | t | t | t | long method | 0 | 5805 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/extensions/rx2/src/main/java/org/apache/cxf/jaxrs/rx2/client/FlowableRxInvoker.java/#L29-L106 | 1 | 585 | 5805 | critical | |
| 4239 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | long method, data class | t | t | t | data class | 0 | 11159 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 4239 | 11159 | minor | |
| 2510 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | data class | t | t | t | 0 | 14684 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 1 | 2510 | 14684 | major | ||
| 1693 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11716 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 1693 | 11716 | minor | ||
| 1431 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | long method | t | t | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 1 | 1431 | 10955 | minor | ||
| 2263 | {"answer": "YES I found bad smells", "the bad smells are: 1. Long Method, 2. Blob, 3. Data Class, 4. Feature Envy, 5. Long Method, 6. Long Method, 7. Long Method, 8. Long Method, 9. Long Method, 10. Long Method, 11. Long Method, 12. Long Method, 13. Long Method, 14. Long Method, 15. Long Method, 16. Long Method, 17. Long Method, 18. Long Method, 19. Long Method, 20. Long Method, 21. Long Method, 22. Long Method, 23. Long Method, 24. Long Method, 25. Long Method, 26. Long Method, 27. Long Method, 28. Long Method, 29. Long Method, 30. Long Method, 31. Long Method, 32. Long Method, 33. Long Method, 34. Long Method, 35. Long Method, 36. Long Method, 37. Long Method, 38. Long Method, 39. Long Method, 40. Long Method, 41. Long Method, 42. Long Method, 43. Long Method, 44. Long Method, 45. Long Method, 46. Long Method, 47. Long Method, 48. Long Method, 49. Long Method, 50. Long Method, 51. Long Method, 52. Long Method, 53. Long Method, 54. Long Method, 55. Long Method, 56. Long Method, 57. Long Method, 58. Long Method, 59. Long Method, 60. Long Method, 61. Long Method, 62. Long Method, 63. Long Method, 64. Long Method, 65. Long Method, 66. Long Method, 67. Long Method, 68. Long Method, 69. Long Method, 70. Long Method, 71. Long Method, 72. Long Method, 73. Long Method, 74. Long Method, 75. Long Method, 76. Long Method, 77. Long Method, 78. Long Method, 79. Long Method, 80. Long Method, 81. Long Method, 82. Long Method, 83. Long Method, 84. Long Method, 85. Long Method, 86. Long Method, 87. Long Method, 88. Long Method, 89. Long Method, 90. Long Method, 91. Long Method, 92. Long Method, 93. Long Method, 94. Long Method, 95. Long Method, 96. Long Method, 97. Long Method, 98. Long Method, 99. Long Method, 100. Long Method, 101. Long Method, 102. Long Method, 103. Long Method, 104. Long Method, 105. Long Method, 106. Long Method, 107. Long Method, 108. Long Method, 109. Long Method, 110. Long Method, 111. Long Method, 112. Long Method, 113. Long Method, 114. Long Method, 115. Long Method, 116. Long Method, 117. Long Method, 118. Long Method, 119. Long Method, 120. Long Method, 121. Long Method, 122. Long Method, 123. Long Method, 124. Long Method, 125. Long Method, 126. Long Method, 127. Long Method, 128. Long Method, 129. Long Method, 130. Long Method, 131. Long Method, 132. Long Method, 133. Long Method, 134. Long Method, 135. Long Method, 136. Long Method, 137. Long Method, 138. Long Method, 139. Long Method, 140. Long Method, 141. Long Method, 142. Long Method, 143. Long Method, 144. Long Method, 145. Long Method, 146. Long Method, 147. Long Method, 148. Long Method, 149. Long Method, 150. Long Method, 151. Long Method, 152. Long Method, 153. Long Method, 154. Long Method, 155. Long Method, 156. Long Method, 157. Long Method, 158. Long Method, 159. Long Method, 160. Long Method, 161. Long Method, 162. Long Method, 163. Long Method, 164. Long Method, 165. Long Method, 166. Long Method, 167. Long Method, 168. Long Method, 169. Long Method, 170. Long Method, 171. Long Method, 172. Long Method, 173. Long Method, 174. Long Method, 175. Long Method, 176. Long Method, 177. Long Method, 178. Long Method, 179. Long Method, 180. Long Method, 181. Long Method, 182. Long Method, 183. Long Method, 184. Long Method, 185. Long Method, 186. Long Method, 187. Long Method, 188. Long Method, 189. Long Method, 190. Long Method, 191. Long Method, 192. Long Method, 193. Long Method, 194. Long Method, 195. Long Method, 196. Long Method, 197. Long Method, 198. Long Method, 199. Long Method, 200. Long Method, 201. Long Method, 202. Long Method, 203. Long Method, 204. Long Method, 205. Long Method, 206. Long Method, 207. Long Method, 208. Long Method, 209. Long Method, 210. Long Method, 211. Long Method, 212. Long Method, 213. Long Method, 214. Long Method, 215. Long Method, 216. Long Method, 217. Long Method, 218. Long Method, 219. Long Method, 220. Long Method, 221. Long Method, 222. Long Method, 223. Long Method, 224. Long Method, 225. Long Method, 226. Long Method, 227. Long Method, 228. Long Method, 229. Long Method, 230. Long Method, 231. Long Method, 232. Long Method, 233. Long Method, 234. Long Method, 235. Long Method, 236. Long Method, 237. Long Method, 238. Long Method, 239. Long Method, 240. Long Method, 241. Long Method, 242. Long Method, 243. Long Method, 244. Long Method, 245. Long Method, 246. Long Method, 247. Long Method, 248. Long Method, 249. Long Method, 250. Long Method, 251. Long Method, 252. Long Method, 253. Long Method, 254. Long Method, 255. Long Method, 256. Long Method, 257. Long Method, 258. Long Method, 259. Long Method, 260. Long Method, 261. Long Method, 262. Long Method, 263. Long Method, 264. Long Method, 265. Long Method, 266. Long Method, 267. Long Method, 268. Long Method, 269. Long Method, 270. Long Method, 271. Long Method, 272. Long Method, 273. Long Method, 274. Long Method, 275. Long Method, 276. Long Method, 277. Long Method, 278. Long Method, 279. Long Method, 280. Long Method, 281. Long Method, 282. Long Method, 283. Long Method, 284. Long Method, 285. Long Method, 286. Long Method, 287. Long Method, 288. Long Method, 289. Long Method, 290. Long Method, 291. Long Method, 292. Long Method, 293. Long Method, 294. Long Method, 295. Long Method, 296. Long Method, 297. Long Method, 298. Long Method, 299. Long Method, 300. Long Method, 301. Long Method, 302. Long Method, 303. Long Method, 304. Long Method, 305. Long Method, 306. Long Method, 307. Long Method, 308. Long Method, 309. Long Method, 310. Long Method, 311. Long Method, 312. Long Method, 313. Long Method, 314. Long Method, 315. Long Method, 316. Long Method, 317. Long Method, 318. Long Method, 319. Long Method, 320. Long Method, 321. Long Method, 322. Long Method, 323. Long Method, 324. Long Method, 325. Long Method, 326. Long Method, 327. Long Method, 328. Long Method, 329. Long Method, 330. Long Method, 331. Long Method, 332. Long Method, 333. Long Method, 334. Long Method, 335. Long Method, 336. Long Method, 337. Long Method, 338. Long Method, 339. Long Method, 340. Long Method, 341. Long Method, 342. Long Method, 343. Long Method, 344. Long Method, 345. Long Method, 346. Long Method, 347. Long Method, 348. Long Method, 349. Long Method, 350. Long Method, 351. Long Method, 352. Long Method, 353. Long Method, 354. Long Method, 355. Long Method, 356. Long Method, 357. Long Method, 358. Long Method, 359. Long Method, 360. Long Method, 361. Long Method, 362. Long Method, 363. Long Method, 364. Long Method, 365. Long Method, 366. Long Method, 367. Long Method, 368. Long Method, 369. Long Method, 370. Long Method, 371. Long Method, 372. Long Method, 373. Long Method, 374. Long Method, 375. Long Method, 376. Long Method, 377. Long Method, 378. Long Method, 379. Long Method, 380. Long Method, 381. Long Method, 382. Long Method, 383. Long Method, 384. Long Method, 385. Long Method, 386. Long Method, 387. Long Method, 388. Long Method, 389. Long Method, 390. Long Method, 391. Long Method, 392. Long Method, 393. Long Method, 394. Long Method, 395. Long Method, 396. Long Method, 397. Long Method, 398. Long Method, 399. Long Method, 400. Long Method, 401. Long Method, 402. Long Method, 403. Long Method, 404. Long Method, 405. Long Method, 406. Long Method, 407. Long Method, 408. Long Method, 409. Long Method, 410. Long Method, 411. Long Method, 412. Long Method, 413. Long Method, 414. Long Method, 415. Long Method, 416. Long Method, 417. Long Method, 418. Long Method, 419. Long Method, 420. Long Method, 421. Long Method, 422. Long Method, 423. Long Method, 424. Long Method, 425. Long Method, 426. Long Method, 427. Long Method, 428. Long Method, 429. Long Method, 430. Long Method, 431. Long Method, 432. Long Method, 433. Long Method, 434. Long Method, 435. Long Method, 436. Long Method, 437. Long Method, 438. Long Method, 439. Long Method, 440. Long Method, 441. Long Method, 442. Long Method, 443. Long Method, 444. Long Method, 445. Long Method, 446. Long Method, 447. Long Method, 448. Long Method, 449. Long Method, 450. Long Method, 451. Long Method, 452. Long Method, 453. Long Method, 454. Long Method, 455. Long Method, 456. Long Method, 457. Long Method, 458. Long Method, 459. Long Method, 460. Long Method, 461. Long Method, 462. Long Method, 463. Long Method, 464. Long Method, 465. Long Method, 466. Long Method, 467. Long Method, 468. Long Method, 469. Long Method, 470. Long Method, 471. Long Method, 472. Long Method, 473. Long Method, 474. Long Method, 475. Long Method, 476. Long Method, 477. Long Method, 478. Long Method, 479. Long Method, 480. Long Method, 481. Long Method, 482. Long Method, 483. Long Method, 484. Long Method, 485. Long Method, 486. Long Method, 487. Long Method, 488. Long Method, 489. Long Method, 490. Long Method, 491. Long Method, 492. Long Method, 493. Long Method, 494. Long Method, 495. Long Method, 496. Long Method, 497. Long Method, 498. Long Method, 499. Long Method, 500. Long Method, 501. Long Method, 502. Long Method, 503. Long Method, 504. Long Method, 505. Long Method, 506. Long Method, 507. Long Method, 508. Long Method, 509. Long Method, 510. Long Method, 511. Long Method, 512. Long Method, 513. Long Method, 514. Long Method, 515. Long Method, 516. Long Method, 517. Long Method, 518. Long Method, 519. Long Method, 520. Long Method, 521. Long Method, 522. Long Method, 523. Long Method, 524. Long Method, 525. Long Method, 526. Long Method, 527. Long Method, 528. Long Method, 529. Long Method, 530. Long Method, 531. Long Method, 532. Long Method, 533. Long Method, 534. Long Method, 535. Long Method, 536. Long Method, 537. Long Method, 538. Long Method, 539. Long Method, 540. Long Method, 541. Long Method, 542. Long Method, 543. Long Method, 544. Long Method, 545. Long Method, 546. Long Method, 547. Long Method, 548. Long Method, 549. Long Method, 550. Long Method, 551. Long Method, 552. Long Method, 553. Long Method, 554. Long Method, 555. Long Method, 556. Long Method, 557. Long Method, 558. Long Method, 559. Long Method, 560. Long Method, 561. Long Method, 562. Long Method, 563. Long Method, 564. Long Method, 565. Long Method, 566. Long Method, 567. Long Method, 568. Long Method, 569. Long Method, 570. Long Method, 571. Long Method, 572. Long Method, 573. Long Method, 574. Long Method, 575. Long Method, 576. Long Method, 577. Long Method, 578. Long Method, 579. Long Method, 580. Long Method, 581. Long Method, 582. Long Method, 583. Long Method, 584. Long Method, 585. Long Method, 586. Long Method, 587. Long Method, 588. Long Method, 589. Long Method, 590. Long Method, 591. Long Method, 592. Long Method, 593. Long Method, 594. Long Method, 595. Long Method, 596. Long Method, 597. Long Method, 598. Long Method, 599. Long Method, 600. Long Method, 601. Long Method, 602. Long Method, 603. Long Method, 604. Long Method, 605. Long Method, 606. Long Method, 607. Long Method, 608. Long Method, 609. Long Method, 610. Long Method, 611. Long Method, 612. Long Method, 613. Long Method, 614. Long Method, 615. Long Method, 616. Long Method, 617. Long Method, 618. Long Method, 619. Long Method, 620. Long Method, 621. Long Method, 622. Long Method, 623. Long Method, 624. Long Method, 625. Long Method, 626. Long Method, 627. Long Method, 628. Long Method, 629. Long Method, 630. Long Method, 631. Long Method, 632. Long Method, 633. Long Method, 634. Data Class, 635. Long Method, 636. Long Method, 637. Data Class, 638. Blob, 639. Data Class, 640. Blob, 641. Data Class, 642. Blob, 643. Data Class, 644. Blob, 645. Data Class, 646. Blob, 647. Data Class, 648. Blob, 649. Data Class, 650. Blob, 651. Data Class, 652. Blob, 653. Data Class, 654. Blob, 655. Data Class, 656. Blob, 657. Data Class, 658. Blob, 659. Data Class, 660. Blob, 661. Data Class, 662. Blob, 663. Data Class, 664. Blob, 665. Data Class, 666. Blob, 667. Data Class, 668. Blob, 669. Data Class, 670. Blob, 671. Data Class, 672. Blob, 673. Data Class, 674. Blob, 675. Data Class, 676. Blob, 677. Data Class, 678. Blob, 679. Data Class, 680. Blob, 681. Data Class, 682. Blob, 683. Data Class, 684. Blob, | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class SplitTableRegionProcedure extends AbstractStateMachineRegionProcedure { private static final Logger LOG = LoggerFactory.getLogger(SplitTableRegionProcedure.class); private Boolean traceEnabled = null; private RegionInfo daughter_1_RI; private RegionInfo daughter_2_RI; private byte[] bestSplitRow; private RegionSplitPolicy splitPolicy; public SplitTableRegionProcedure() { // Required by the Procedure framework to create the procedure on replay } public SplitTableRegionProcedure(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { super(env, regionToSplit); preflightChecks(env, true); // When procedure goes to run in its prepare step, it also does these checkOnline checks. Here // we fail-fast on construction. There it skips the split with just a warning. checkOnline(env, regionToSplit); this.bestSplitRow = splitRow; checkSplittable(env, regionToSplit, bestSplitRow); final TableName table = regionToSplit.getTable(); final long rid = getDaughterRegionIdTimestamp(regionToSplit); this.daughter_1_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(regionToSplit.getStartKey()) .setEndKey(bestSplitRow) .setSplit(false) .setRegionId(rid) .build(); this.daughter_2_RI = RegionInfoBuilder.newBuilder(table) .setStartKey(bestSplitRow) .setEndKey(regionToSplit.getEndKey()) .setSplit(false) .setRegionId(rid) .build(); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); if(htd.getRegionSplitPolicyClassName() != null) { // Since we don't have region reference here, creating the split policy instance without it. // This can be used to invoke methods which don't require Region reference. This instantiation // of a class on Master-side though it only makes sense on the RegionServer-side is // for Phoenix Local Indexing. Refer HBASE-12583 for more information. Class clazz = RegionSplitPolicy.getSplitPolicyClass(htd, env.getMasterConfiguration()); this.splitPolicy = ReflectionUtils.newInstance(clazz, env.getMasterConfiguration()); } } @Override protected LockState acquireLock(final MasterProcedureEnv env) { if (env.getProcedureScheduler().waitRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI)) { try { LOG.debug(LockState.LOCK_EVENT_WAIT + " " + env.getProcedureScheduler().dumpLocks()); } catch (IOException e) { // Ignore, just for logging } return LockState.LOCK_EVENT_WAIT; } return LockState.LOCK_ACQUIRED; } @Override protected void releaseLock(final MasterProcedureEnv env) { env.getProcedureScheduler().wakeRegions(this, getTableName(), getParentRegion(), daughter_1_RI, daughter_2_RI); } /** * Check whether the region is splittable * @param env MasterProcedureEnv * @param regionToSplit parent Region to be split * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS * @throws IOException */ private void checkSplittable(final MasterProcedureEnv env, final RegionInfo regionToSplit, final byte[] splitRow) throws IOException { // Ask the remote RS if this region is splittable. // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time. if(regionToSplit.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) { throw new IllegalArgumentException ("Can't invoke split on non-default regions directly"); } RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); IOException splittableCheckIOE = null; boolean splittable = false; if (node != null) { try { if (bestSplitRow == null || bestSplitRow.length == 0) { LOG .info("splitKey isn't explicitly specified, will try to find a best split key from RS"); } // Always set bestSplitRow request as true here, // need to call Region#checkSplit to check it splittable or not GetRegionInfoResponse response = AssignmentManagerUtil.getRegionInfoResponse(env, node.getRegionLocation(), node.getRegionInfo(), true); if(bestSplitRow == null || bestSplitRow.length == 0) { bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null; } splittable = response.hasSplittable() && response.getSplittable(); if (LOG.isDebugEnabled()) { LOG.debug("Splittable=" + splittable + " " + node.toShortString()); } } catch (IOException e) { splittableCheckIOE = e; } } if (!splittable) { IOException e = new DoNotRetryIOException(regionToSplit.getShortNameToLog() + " NOT splittable"); if (splittableCheckIOE != null) { e.initCause(splittableCheckIOE); } throw e; } if (bestSplitRow == null || bestSplitRow.length == 0) { throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null, " + "maybe table is too small for auto split. For force split, try specifying split row"); } if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) { throw new DoNotRetryIOException( "Split row is equal to startkey: " + Bytes.toStringBinary(splitRow)); } if (!regionToSplit.containsRow(bestSplitRow)) { throw new DoNotRetryIOException("Split row is not inside region key range splitKey:" + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit); } } /** * Calculate daughter regionid to use. * @param hri Parent {@link RegionInfo} * @return Daughter region id (timestamp) to use. */ private static long getDaughterRegionIdTimestamp(final RegionInfo hri) { long rid = EnvironmentEdgeManager.currentTime(); // Regionid is timestamp. Can't be less than that of parent else will insert // at wrong location in hbase:meta (See HBASE-710). if (rid < hri.getRegionId()) { LOG.warn("Clock skew; parent regions id is " + hri.getRegionId() + " but current time here is " + rid); rid = hri.getRegionId() + 1; } return rid; } private void removeNonDefaultReplicas(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.removeNonDefaultReplicas(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private void checkClosedRegions(MasterProcedureEnv env) throws IOException { // theoretically this should not happen any more after we use TRSP, but anyway let's add a check // here AssignmentManagerUtil.checkClosedRegion(env, getParentRegion()); } @Override protected Flow executeFromState(MasterProcedureEnv env, SplitTableRegionState state) throws InterruptedException { LOG.trace("{} execute state={}", this, state); try { switch (state) { case SPLIT_TABLE_REGION_PREPARE: if (prepareSplitRegion(env)) { setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION); break; } else { return Flow.NO_MORE_STATE; } case SPLIT_TABLE_REGION_PRE_OPERATION: preSplitRegion(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CLOSE_PARENT_REGION); break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: addChildProcedure(createUnassignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS); break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: checkClosedRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS); break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: removeNonDefaultReplicas(env); createDaughterRegions(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE); break; case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: writeMaxSequenceIdFile(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: preSplitRegionBeforeMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_UPDATE_META); break; case SPLIT_TABLE_REGION_UPDATE_META: updateMeta(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META); break; case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: preSplitRegionAfterMETA(env); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS); break; case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: addChildProcedure(createAssignProcedures(env)); setNextState(SplitTableRegionState.SPLIT_TABLE_REGION_POST_OPERATION); break; case SPLIT_TABLE_REGION_POST_OPERATION: postSplitRegion(env); return Flow.NO_MORE_STATE; default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { String msg = "Splitting " + getParentRegion().getEncodedName() + ", " + this; if (!isRollbackSupported(state)) { // We reach a state that cannot be rolled back. We just need to keep retrying. LOG.warn(msg, e); } else { LOG.error(msg, e); setFailure("master-split-regions", e); } } // if split fails, need to call ((HRegion)parent).clearSplit() when it is a force split return Flow.HAS_MORE_STATE; } /** * To rollback {@link SplitTableRegionProcedure}, an AssignProcedure is asynchronously * submitted for parent region to be split (rollback doesn't wait on the completion of the * AssignProcedure) . This can be improved by changing rollback() to support sub-procedures. * See HBASE-19851 for details. */ @Override protected void rollbackState(final MasterProcedureEnv env, final SplitTableRegionState state) throws IOException, InterruptedException { if (isTraceEnabled()) { LOG.trace(this + " rollback state=" + state); } try { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // PONR throw new UnsupportedOperationException(this + " unhandled state=" + state); case SPLIT_TABLE_REGION_PRE_OPERATION_BEFORE_META: break; case SPLIT_TABLE_REGION_CREATE_DAUGHTER_REGIONS: case SPLIT_TABLE_REGION_WRITE_MAX_SEQUENCE_ID_FILE: // Doing nothing, as re-open parent region would clean up daughter region directories. break; case SPLIT_TABLE_REGIONS_CHECK_CLOSED_REGIONS: // Doing nothing, in SPLIT_TABLE_REGION_CLOSE_PARENT_REGION, // we will bring parent region online break; case SPLIT_TABLE_REGION_CLOSE_PARENT_REGION: openParentRegion(env); break; case SPLIT_TABLE_REGION_PRE_OPERATION: postRollBackSplitRegion(env); break; case SPLIT_TABLE_REGION_PREPARE: break; // nothing to do default: throw new UnsupportedOperationException(this + " unhandled state=" + state); } } catch (IOException e) { // This will be retried. Unless there is a bug in the code, // this should be just a "temporary error" (e.g. network down) LOG.warn("pid=" + getProcId() + " failed rollback attempt step " + state + " for splitting the region " + getParentRegion().getEncodedName() + " in table " + getTableName(), e); throw e; } } /* * Check whether we are in the state that can be rollback */ @Override protected boolean isRollbackSupported(final SplitTableRegionState state) { switch (state) { case SPLIT_TABLE_REGION_POST_OPERATION: case SPLIT_TABLE_REGION_OPEN_CHILD_REGIONS: case SPLIT_TABLE_REGION_PRE_OPERATION_AFTER_META: case SPLIT_TABLE_REGION_UPDATE_META: // It is not safe to rollback if we reach to these states. return false; default: break; } return true; } @Override protected SplitTableRegionState getState(final int stateId) { return SplitTableRegionState.forNumber(stateId); } @Override protected int getStateId(final SplitTableRegionState state) { return state.getNumber(); } @Override protected SplitTableRegionState getInitialState() { return SplitTableRegionState.SPLIT_TABLE_REGION_PREPARE; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData.Builder splitTableRegionMsg = MasterProcedureProtos.SplitTableRegionStateData.newBuilder() .setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser())) .setParentRegionInfo(ProtobufUtil.toRegionInfo(getRegion())) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_1_RI)) .addChildRegionInfo(ProtobufUtil.toRegionInfo(daughter_2_RI)); serializer.serialize(splitTableRegionMsg.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); final MasterProcedureProtos.SplitTableRegionStateData splitTableRegionsMsg = serializer.deserialize(MasterProcedureProtos.SplitTableRegionStateData.class); setUser(MasterProcedureUtil.toUserInfo(splitTableRegionsMsg.getUserInfo())); setRegion(ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getParentRegionInfo())); assert(splitTableRegionsMsg.getChildRegionInfoCount() == 2); daughter_1_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(0)); daughter_2_RI = ProtobufUtil.toRegionInfo(splitTableRegionsMsg.getChildRegionInfo(1)); } @Override public void toStringClassDetails(StringBuilder sb) { sb.append(getClass().getSimpleName()); sb.append(" table="); sb.append(getTableName()); sb.append(", parent="); sb.append(getParentRegion().getShortNameToLog()); sb.append(", daughterA="); sb.append(daughter_1_RI.getShortNameToLog()); sb.append(", daughterB="); sb.append(daughter_2_RI.getShortNameToLog()); } private RegionInfo getParentRegion() { return getRegion(); } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_SPLIT; } @Override protected ProcedureMetrics getProcedureMetrics(MasterProcedureEnv env) { return env.getAssignmentManager().getAssignmentManagerMetrics().getSplitProcMetrics(); } private byte[] getSplitRow() { return daughter_2_RI.getStartKey(); } private static final State[] EXPECTED_SPLIT_STATES = new State[] { State.OPEN, State.CLOSED }; /** * Prepare to Split region. * @param env MasterProcedureEnv */ @VisibleForTesting public boolean prepareSplitRegion(final MasterProcedureEnv env) throws IOException { // Fail if we are taking snapshot for the given table if (env.getMasterServices().getSnapshotManager() .isTakingSnapshot(getParentRegion().getTable())) { setFailure(new IOException("Skip splitting region " + getParentRegion().getShortNameToLog() + ", because we are taking snapshot for the table " + getParentRegion().getTable())); return false; } // Check whether the region is splittable RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionStateNode(getParentRegion()); if (node == null) { throw new UnknownRegionException(getParentRegion().getRegionNameAsString()); } RegionInfo parentHRI = node.getRegionInfo(); if (parentHRI == null) { LOG.info("Unsplittable; parent region is null; node={}", node); return false; } // Lookup the parent HRI state from the AM, which has the latest updated info. // Protect against the case where concurrent SPLIT requests came in and succeeded // just before us. if (node.isInState(State.SPLIT)) { LOG.info("Split of " + parentHRI + " skipped; state is already SPLIT"); return false; } if (parentHRI.isSplit() || parentHRI.isOffline()) { LOG.info("Split of " + parentHRI + " skipped because offline/split."); return false; } // expected parent to be online or closed if (!node.isInState(EXPECTED_SPLIT_STATES)) { // We may have SPLIT already? setFailure(new IOException("Split " + parentHRI.getRegionNameAsString() + " FAILED because state=" + node.getState() + "; expected " + Arrays.toString(EXPECTED_SPLIT_STATES))); return false; } // Since we have the lock and the master is coordinating the operation // we are always able to split the region if (!env.getMasterServices().isSplitOrMergeEnabled(MasterSwitchType.SPLIT)) { LOG.warn("pid=" + getProcId() + " split switch is off! skip split of " + parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed due to split switch off")); return false; } if (!env.getMasterServices().getTableDescriptors().get(getTableName()).isSplitEnabled()) { LOG.warn("pid={}, split is disabled for the table! Skipping split of {}", getProcId(), parentHRI); setFailure(new IOException("Split region " + parentHRI.getRegionNameAsString() + " failed as region split is disabled for the table")); return false; } // set node state as SPLITTING node.setState(State.SPLITTING); return true; } /** * Action before splitting region in a table. * @param env MasterProcedureEnv */ private void preSplitRegion(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitRegionAction(getTableName(), getSplitRow(), getUser()); } // TODO: Clean up split and merge. Currently all over the place. // Notify QuotaManager and RegionNormalizer try { env.getMasterServices().getMasterQuotaManager().onRegionSplit(this.getParentRegion()); } catch (QuotaExceededException e) { env.getMasterServices().getRegionNormalizer().planSkipped(this.getParentRegion(), NormalizationPlan.PlanType.SPLIT); throw e; } } /** * Action after rollback a split table region action. * @param env MasterProcedureEnv */ private void postRollBackSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postRollBackSplitRegionAction(getUser()); } } /** * Rollback close parent region */ private void openParentRegion(MasterProcedureEnv env) throws IOException { AssignmentManagerUtil.reopenRegionsForRollback(env, Collections.singletonList((getParentRegion())), getRegionReplication(env), getParentRegionServerName(env)); } /** * Create daughter regions */ @VisibleForTesting public void createDaughterRegions(final MasterProcedureEnv env) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Path tabledir = FSUtils.getTableDir(mfs.getRootDir(), getTableName()); final FileSystem fs = mfs.getFileSystem(); HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem( env.getMasterConfiguration(), fs, tabledir, getParentRegion(), false); regionFs.createSplitsDir(); Pair expectedReferences = splitStoreFiles(env, regionFs); assertReferenceFileCount(fs, expectedReferences.getFirst(), regionFs.getSplitsDir(daughter_1_RI)); //Move the files from the temporary .splits to the final /table/region directory regionFs.commitDaughterRegion(daughter_1_RI); assertReferenceFileCount(fs, expectedReferences.getFirst(), new Path(tabledir, daughter_1_RI.getEncodedName())); assertReferenceFileCount(fs, expectedReferences.getSecond(), regionFs.getSplitsDir(daughter_2_RI)); regionFs.commitDaughterRegion(daughter_2_RI); assertReferenceFileCount(fs, expectedReferences.getSecond(), new Path(tabledir, daughter_2_RI.getEncodedName())); } /** * Create Split directory * @param env MasterProcedureEnv */ private Pair splitStoreFiles(final MasterProcedureEnv env, final HRegionFileSystem regionFs) throws IOException { final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); final Configuration conf = env.getMasterConfiguration(); // The following code sets up a thread pool executor with as many slots as // there's files to split. It then fires up everything, waits for // completion and finally checks for any exception // // Note: splitStoreFiles creates daughter region dirs under the parent splits dir // Nothing to unroll here if failure -- re-run createSplitsDir will // clean this up. int nbFiles = 0; final Map> files = new HashMap>(regionFs.getFamilies().size()); for (String family: regionFs.getFamilies()) { Collection sfis = regionFs.getStoreFiles(family); if (sfis == null) continue; Collection filteredSfis = null; for (StoreFileInfo sfi: sfis) { // Filter. There is a lag cleaning up compacted reference files. They get cleared // after a delay in case outstanding Scanners still have references. Because of this, // the listing of the Store content may have straggler reference files. Skip these. // It should be safe to skip references at this point because we checked above with // the region if it thinks it is splittable and if we are here, it thinks it is // splitable. if (sfi.isReference()) { LOG.info("Skipping split of " + sfi + "; presuming ready for archiving."); continue; } if (filteredSfis == null) { filteredSfis = new ArrayList(sfis.size()); files.put(family, filteredSfis); } filteredSfis.add(sfi); nbFiles++; } } if (nbFiles == 0) { // no file needs to be splitted. return new Pair(0,0); } // Max #threads is the smaller of the number of storefiles or the default max determined above. int maxThreads = Math.min( conf.getInt(HConstants.REGION_SPLIT_THREADS_MAX, conf.getInt(HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT)), nbFiles); LOG.info("pid=" + getProcId() + " splitting " + nbFiles + " storefiles, region=" + getParentRegion().getShortNameToLog() + ", threads=" + maxThreads); final ExecutorService threadPool = Executors.newFixedThreadPool( maxThreads, Threads.getNamedThreadFactory("StoreFileSplitter-%1$d")); final List>> futures = new ArrayList>>(nbFiles); TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); // Split each store file. for (Map.Entry> e : files.entrySet()) { byte[] familyName = Bytes.toBytes(e.getKey()); final ColumnFamilyDescriptor hcd = htd.getColumnFamily(familyName); final Collection storeFiles = e.getValue(); if (storeFiles != null && storeFiles.size() > 0) { for (StoreFileInfo storeFileInfo : storeFiles) { // As this procedure is running on master, use CacheConfig.DISABLED means // don't cache any block. StoreFileSplitter sfs = new StoreFileSplitter(regionFs, familyName, new HStoreFile(mfs.getFileSystem(), storeFileInfo, conf, CacheConfig.DISABLED, hcd.getBloomFilterType(), true)); futures.add(threadPool.submit(sfs)); } } } // Shutdown the pool threadPool.shutdown(); // Wait for all the tasks to finish. // When splits ran on the RegionServer, how-long-to-wait-configuration was named // hbase.regionserver.fileSplitTimeout. If set, use its value. long fileSplitTimeout = conf.getLong("hbase.master.fileSplitTimeout", conf.getLong("hbase.regionserver.fileSplitTimeout", 600000)); try { boolean stillRunning = !threadPool.awaitTermination(fileSplitTimeout, TimeUnit.MILLISECONDS); if (stillRunning) { threadPool.shutdownNow(); // wait for the thread to shutdown completely. while (!threadPool.isTerminated()) { Thread.sleep(50); } throw new IOException("Took too long to split the" + " files and create the references, aborting split"); } } catch (InterruptedException e) { throw (InterruptedIOException)new InterruptedIOException().initCause(e); } int daughterA = 0; int daughterB = 0; // Look for any exception for (Future> future : futures) { try { Pair p = future.get(); daughterA += p.getFirst() != null ? 1 : 0; daughterB += p.getSecond() != null ? 1 : 0; } catch (InterruptedException e) { throw (InterruptedIOException) new InterruptedIOException().initCause(e); } catch (ExecutionException e) { throw new IOException(e); } } if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " split storefiles for region " + getParentRegion().getShortNameToLog() + " Daughter A: " + daughterA + " storefiles, Daughter B: " + daughterB + " storefiles."); } return new Pair(daughterA, daughterB); } private void assertReferenceFileCount(final FileSystem fs, final int expectedReferenceFileCount, final Path dir) throws IOException { if (expectedReferenceFileCount != 0 && expectedReferenceFileCount != FSUtils.getRegionReferenceFileCount(fs, dir)) { throw new IOException("Failing split. Expected reference file count isn't equal."); } } private Pair splitStoreFile(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting started for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } final byte[] splitRow = getSplitRow(); final String familyName = Bytes.toString(family); final Path path_first = regionFs.splitStoreFile(this.daughter_1_RI, familyName, sf, splitRow, false, splitPolicy); final Path path_second = regionFs.splitStoreFile(this.daughter_2_RI, familyName, sf, splitRow, true, splitPolicy); if (LOG.isDebugEnabled()) { LOG.debug("pid=" + getProcId() + " splitting complete for store file: " + sf.getPath() + " for region: " + getParentRegion().getShortNameToLog()); } return new Pair(path_first, path_second); } /** * Utility class used to do the file splitting / reference writing * in parallel instead of sequentially. */ private class StoreFileSplitter implements Callable> { private final HRegionFileSystem regionFs; private final byte[] family; private final HStoreFile sf; /** * Constructor that takes what it needs to split * @param regionFs the file system * @param family Family that contains the store file * @param sf which file */ public StoreFileSplitter(HRegionFileSystem regionFs, byte[] family, HStoreFile sf) { this.regionFs = regionFs; this.sf = sf; this.family = family; } @Override public Pair call() throws IOException { return splitStoreFile(regionFs, family, sf); } } /** * Post split region actions before the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionBeforeMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final List metaEntries = new ArrayList(); final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitBeforeMETAAction(getSplitRow(), metaEntries, getUser()); try { for (Mutation p : metaEntries) { RegionInfo.parseRegionName(p.getRow()); } } catch (IOException e) { LOG.error("pid=" + getProcId() + " row key of mutation from coprocessor not parsable as " + "region name." + "Mutations from coprocessor should only for hbase:meta table."); throw e; } } } /** * Add daughter regions to META * @param env MasterProcedureEnv */ private void updateMeta(final MasterProcedureEnv env) throws IOException { env.getAssignmentManager().markRegionAsSplit(getParentRegion(), getParentRegionServerName(env), daughter_1_RI, daughter_2_RI); } /** * Pre split region actions after the Point-of-No-Return step * @param env MasterProcedureEnv **/ private void preSplitRegionAfterMETA(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.preSplitAfterMETAAction(getUser()); } } /** * Post split region actions * @param env MasterProcedureEnv **/ private void postSplitRegion(final MasterProcedureEnv env) throws IOException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { cpHost.postCompletedSplitRegionAction(daughter_1_RI, daughter_2_RI, getUser()); } } private ServerName getParentRegionServerName(final MasterProcedureEnv env) { return env.getMasterServices().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(getParentRegion()); } private TransitRegionStateProcedure[] createUnassignProcedures(MasterProcedureEnv env) throws IOException { return AssignmentManagerUtil.createUnassignProceduresForSplitOrMerge(env, Stream.of(getParentRegion()), getRegionReplication(env)); } private TransitRegionStateProcedure[] createAssignProcedures(MasterProcedureEnv env) throws IOException { List hris = new ArrayList(2); hris.add(daughter_1_RI); hris.add(daughter_2_RI); return AssignmentManagerUtil.createAssignProceduresForOpeningNewRegions(env, hris, getRegionReplication(env), getParentRegionServerName(env)); } private int getRegionReplication(final MasterProcedureEnv env) throws IOException { final TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(getTableName()); return htd.getRegionReplication(); } private void writeMaxSequenceIdFile(MasterProcedureEnv env) throws IOException { FileSystem walFS = env.getMasterServices().getMasterWalManager().getFileSystem(); long maxSequenceId = WALSplitter.getMaxRegionSequenceId(walFS, getWALRegionDir(env, getParentRegion())); if (maxSequenceId > 0) { WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_1_RI), maxSequenceId); WALSplitter.writeRegionSequenceIdFile(walFS, getWALRegionDir(env, daughter_2_RI), maxSequenceId); } } /** * The procedure could be restarted from a different machine. If the variable is null, we need to * retrieve it. * @return traceEnabled */ private boolean isTraceEnabled() { if (traceEnabled == null) { traceEnabled = LOG.isTraceEnabled(); } return traceEnabled; } @Override protected boolean abort(MasterProcedureEnv env) { // Abort means rollback. We can't rollback all steps. HBASE-18018 added abort to all // Procedures. Here is a Procedure that has a PONR and cannot be aborted wants it enters this // range of steps; what do we do for these should an operator want to cancel them? HBASE-20022. return isRollbackSupported(getCurrentState())? super.abort(env): false; } } |
blob | Long Method, 2 Blob, 3 Data Class, 4 Feature Envy, 5 Long Method, 6 Long Method, 7 Long Method, 8 Long Method, 9 Long Method, | t | f | t | . Long Method, 3. Data Class, 4. Feature Envy, 5. Long Method, 6. Long Method, 7. Long Method, 8. Long Method, 9. Long Method, | 0 | 13723 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-server/src/main/java/org/apache/hadoop/hbase/master/assignment/SplitTableRegionProcedure.java/#L91-L897 | 1 | 2263 | 13723 | major | |
| 1314 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
long method | long method | t | t | t | 0 | 10686 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1314 | 10686 | minor | ||
| 2184 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ObjectRetrievalFailureException extends DataRetrievalFailureException { @Nullable private final Object persistentClass; @Nullable private final Object identifier; /** * Create a general ObjectRetrievalFailureException with the given message, * without any information on the affected object. * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException(String msg, Throwable cause) { super(msg, cause); this.persistentClass = null; this.identifier = null; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(Class persistentClass, Object identifier) { this(persistentClass, identifier, "Object of class [" + persistentClass.getName() + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClass the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( Class persistentClass, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClass; this.identifier = identifier; } /** * Create a new ObjectRetrievalFailureException for the given object, * with the default "not found" message. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved */ public ObjectRetrievalFailureException(String persistentClassName, Object identifier) { this(persistentClassName, identifier, "Object of class [" + persistentClassName + "] with identifier [" + identifier + "]: not found", null); } /** * Create a new ObjectRetrievalFailureException for the given object, * with the given explicit message and exception. * @param persistentClassName the name of the persistent class * @param identifier the ID of the object that should have been retrieved * @param msg the detail message * @param cause the source exception */ public ObjectRetrievalFailureException( String persistentClassName, Object identifier, String msg, @Nullable Throwable cause) { super(msg, cause); this.persistentClass = persistentClassName; this.identifier = identifier; } /** * Return the persistent class of the object that was not found. * If no Class was specified, this method returns null. */ @Nullable public Class getPersistentClass() { return (this.persistentClass instanceof Class ? (Class) this.persistentClass : null); } /** * Return the name of the persistent class of the object that was not found. * Will work for both Class objects and String names. */ @Nullable public String getPersistentClassName() { if (this.persistentClass instanceof Class) { return ((Class) this.persistentClass).getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object that was not found. */ @Nullable public Object getIdentifier() { return this.identifier; } } |
data class | blob, data class | t | t | t | blob | 0 | 13426 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/ObjectRetrievalFailureException.java/#L29-L137 | 1 | 2184 | 13426 | minor | |
| 140 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | 1. data class | t | t | t | 0 | 1770 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 140 | 1770 | major | ||
| 1527 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | Data Class | t | f | t | 0 | 11193 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 1527 | 11193 | minor | ||
| 1553 | { "message": "YES I found bad smells", "the bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class DocumentsWriterDeleteQueue implements Accountable { // the current end (latest delete operation) in the delete queue: private volatile Node tail; /** Used to record deletes against all prior (already written to disk) segments. Whenever any segment flushes, we bundle up this set of * deletes and insert into the buffered updates stream before the newly flushed segment(s). */ private final DeleteSlice globalSlice; private final BufferedUpdates globalBufferedUpdates; // only acquired to update the global deletes, pkg-private for access by tests: final ReentrantLock globalBufferLock = new ReentrantLock(); final long generation; /** Generates the sequence number that IW returns to callers changing the index, showing the effective serialization of all operations. */ private final AtomicLong nextSeqNo; private final InfoStream infoStream; // for asserts long maxSeqNo = Long.MAX_VALUE; DocumentsWriterDeleteQueue(InfoStream infoStream) { // seqNo must start at 1 because some APIs negate this to also return a boolean this(infoStream, 0, 1); } DocumentsWriterDeleteQueue(InfoStream infoStream, long generation, long startSeqNo) { this(infoStream, new BufferedUpdates("global"), generation, startSeqNo); } DocumentsWriterDeleteQueue(InfoStream infoStream, BufferedUpdates globalBufferedUpdates, long generation, long startSeqNo) { this.infoStream = infoStream; this.globalBufferedUpdates = globalBufferedUpdates; this.generation = generation; this.nextSeqNo = new AtomicLong(startSeqNo); /* * we use a sentinel instance as our initial tail. No slice will ever try to * apply this tail since the head is always omitted. */ tail = new Node<>(null); // sentinel globalSlice = new DeleteSlice(tail); } long addDelete(Query... queries) { long seqNo = add(new QueryArrayNode(queries)); tryApplyGlobalSlice(); return seqNo; } long addDelete(Term... terms) { long seqNo = add(new TermArrayNode(terms)); tryApplyGlobalSlice(); return seqNo; } long addDocValuesUpdates(DocValuesUpdate... updates) { long seqNo = add(new DocValuesUpdatesNode(updates)); tryApplyGlobalSlice(); return seqNo; } static Node newNode(Term term) { return new TermNode(term); } static Node newNode(DocValuesUpdate... updates) { return new DocValuesUpdatesNode(updates); } /** * invariant for document update */ long add(Node deleteNode, DeleteSlice slice) { long seqNo = add(deleteNode); /* * this is an update request where the term is the updated documents * delTerm. in that case we need to guarantee that this insert is atomic * with regards to the given delete slice. This means if two threads try to * update the same document with in turn the same delTerm one of them must * win. By taking the node we have created for our del term as the new tail * it is guaranteed that if another thread adds the same right after us we * will apply this delete next time we update our slice and one of the two * competing updates wins! */ slice.sliceTail = deleteNode; assert slice.sliceHead != slice.sliceTail : "slice head and tail must differ after add"; tryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe // we can do it just every n times or so? return seqNo; } synchronized long add(Node newNode) { tail.next = newNode; this.tail = newNode; return getNextSequenceNumber(); } boolean anyChanges() { globalBufferLock.lock(); try { /* * check if all items in the global slice were applied * and if the global slice is up-to-date * and if globalBufferedUpdates has changes */ return globalBufferedUpdates.any() || !globalSlice.isEmpty() || globalSlice.sliceTail != tail || tail.next != null; } finally { globalBufferLock.unlock(); } } void tryApplyGlobalSlice() { if (globalBufferLock.tryLock()) { /* * The global buffer must be locked but we don't need to update them if * there is an update going on right now. It is sufficient to apply the * deletes that have been added after the current in-flight global slices * tail the next time we can get the lock! */ try { if (updateSliceNoSeqNo(globalSlice)) { globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } } finally { globalBufferLock.unlock(); } } } FrozenBufferedUpdates freezeGlobalBuffer(DeleteSlice callerSlice) throws IOException { globalBufferLock.lock(); /* * Here we freeze the global buffer so we need to lock it, apply all * deletes in the queue and reset the global slice to let the GC prune the * queue. */ final Node currentTail = tail; // take the current tail make this local any // Changes after this call are applied later // and not relevant here if (callerSlice != null) { // Update the callers slices so we are on the same page callerSlice.sliceTail = currentTail; } try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } if (globalBufferedUpdates.any()) { final FrozenBufferedUpdates packet = new FrozenBufferedUpdates(infoStream, globalBufferedUpdates, null); globalBufferedUpdates.clear(); return packet; } else { return null; } } finally { globalBufferLock.unlock(); } } DeleteSlice newSlice() { return new DeleteSlice(tail); } /** Negative result means there were new deletes since we last applied */ synchronized long updateSlice(DeleteSlice slice) { long seqNo = getNextSequenceNumber(); if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; seqNo = -seqNo; } return seqNo; } /** Just like updateSlice, but does not assign a sequence number */ boolean updateSliceNoSeqNo(DeleteSlice slice) { if (slice.sliceTail != tail) { // new deletes arrived since we last checked slice.sliceTail = tail; return true; } return false; } static class DeleteSlice { // No need to be volatile, slices are thread captive (only accessed by one thread)! Node sliceHead; // we don't apply this one Node sliceTail; DeleteSlice(Node currentTail) { assert currentTail != null; /* * Initially this is a 0 length slice pointing to the 'current' tail of * the queue. Once we update the slice we only need to assign the tail and * have a new slice */ sliceHead = sliceTail = currentTail; } void apply(BufferedUpdates del, int docIDUpto) { if (sliceHead == sliceTail) { // 0 length slice return; } /* * When we apply a slice we take the head and get its next as our first * item to apply and continue until we applied the tail. If the head and * tail in this slice are not equal then there will be at least one more * non-null node in the slice! */ Node current = sliceHead; do { current = current.next; assert current != null : "slice property violated between the head on the tail must not be a null node"; current.apply(del, docIDUpto); } while (current != sliceTail); reset(); } void reset() { // Reset to a 0 length slice sliceHead = sliceTail; } /** * Returns true iff the given node is identical to the the slices tail, * otherwise false. */ boolean isTail(Node node) { return sliceTail == node; } /** * Returns true iff the given item is identical to the item * hold by the slices tail, otherwise false. */ boolean isTailItem(Object object) { return sliceTail.item == object; } boolean isEmpty() { return sliceHead == sliceTail; } } public int numGlobalTermDeletes() { return globalBufferedUpdates.numTermDeletes.get(); } void clear() { globalBufferLock.lock(); try { final Node currentTail = tail; globalSlice.sliceHead = globalSlice.sliceTail = currentTail; globalBufferedUpdates.clear(); } finally { globalBufferLock.unlock(); } } static class Node { volatile Node next; final T item; Node(T item) { this.item = item; } void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { throw new IllegalStateException("sentinel item must never be applied"); } boolean isDelete() { return true; } } private static final class TermNode extends Node { TermNode(Term term) { super(term); } @Override void apply(BufferedUpdates bufferedDeletes, int docIDUpto) { bufferedDeletes.addTerm(item, docIDUpto); } @Override public String toString() { return "del=" + item; } } private static final class QueryArrayNode extends Node { QueryArrayNode(Query[] query) { super(query); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Query query : item) { bufferedUpdates.addQuery(query, docIDUpto); } } } private static final class TermArrayNode extends Node { TermArrayNode(Term[] term) { super(term); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (Term term : item) { bufferedUpdates.addTerm(term, docIDUpto); } } @Override public String toString() { return "dels=" + Arrays.toString(item); } } private static final class DocValuesUpdatesNode extends Node { DocValuesUpdatesNode(DocValuesUpdate... updates) { super(updates); } @Override void apply(BufferedUpdates bufferedUpdates, int docIDUpto) { for (DocValuesUpdate update : item) { switch (update.type) { case NUMERIC: bufferedUpdates.addNumericUpdate((NumericDocValuesUpdate) update, docIDUpto); break; case BINARY: bufferedUpdates.addBinaryUpdate((BinaryDocValuesUpdate) update, docIDUpto); break; default: throw new IllegalArgumentException(update.type + " DocValues updates not supported yet!"); } } } @Override boolean isDelete() { return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("docValuesUpdates: "); if (item.length > 0) { sb.append("term=").append(item[0].term).append("; updates: ["); for (DocValuesUpdate update : item) { sb.append(update.field).append(':').append(update.valueToString()).append(','); } sb.setCharAt(sb.length()-1, ']'); } return sb.toString(); } } private boolean forceApplyGlobalSlice() { globalBufferLock.lock(); final Node currentTail = tail; try { if (globalSlice.sliceTail != currentTail) { globalSlice.sliceTail = currentTail; globalSlice.apply(globalBufferedUpdates, BufferedUpdates.MAX_INT); } return globalBufferedUpdates.any(); } finally { globalBufferLock.unlock(); } } public int getBufferedUpdatesTermsSize() { globalBufferLock.lock(); try { forceApplyGlobalSlice(); return globalBufferedUpdates.deleteTerms.size(); } finally { globalBufferLock.unlock(); } } @Override public long ramBytesUsed() { return globalBufferedUpdates.ramBytesUsed(); } @Override public String toString() { return "DWDQ: [ generation: " + generation + " ]"; } public long getNextSequenceNumber() { long seqNo = nextSeqNo.getAndIncrement(); assert seqNo < maxSeqNo: "seqNo=" + seqNo + " vs maxSeqNo=" + maxSeqNo; return seqNo; } public long getLastSequenceNumber() { return nextSeqNo.get()-1; } /** Inserts a gap in the sequence numbers. This is used by IW during flush or commit to ensure any in-flight threads get sequence numbers * inside the gap */ public void skipSequenceNumbers(long jump) { nextSeqNo.addAndGet(jump); } } |
blob | Blob, Long Method | t | f | t | Long Method | 0 | 11272 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterDeleteQueue.java/#L71-L495 | 1 | 1553 | 11272 | major | |
| 95 | { "output": "YES I found bad smells\nthe bad smells are: Blob, Long Method, Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class QueryItemTreeControl extends Composite { public static interface QueryItemDoubleClickedListener { public void queryItemDoubleClicked(QueryItem queryItem); } public static interface QueryItemSelectionListener { public void queryItemSelected(QueryItem queryItem); } /* * a reference to all the projects on the server */ private final Project[] projects; /* * a sorted array of the names of the currently "active" projects, where * active means the user has added the project to team explorer */ private final String[] activeProjectNames; /* * the tree viewer this composite is based around */ private TreeViewer treeViewer; /* * used to track the currently selected query in the tree */ private QueryItem selectedQueryItem; private final QueryItemType itemTypes; /* * listener set */ private final Set queryDoubleClickListeners = new HashSet(); private final Set querySelectionListeners = new HashSet(); public QueryItemTreeControl( final Composite parent, final int style, final TFSServer server, final Project[] projects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { this( parent, style, projects, ProjectInfoHelper.getProjectNames(server.getProjectCache().getActiveTeamProjects()), initialQueryItem, itemTypes); } public QueryItemTreeControl( final Composite parent, final int style, final Project[] projects, final String[] activeProjects, final QueryItem initialQueryItem, final QueryItemType itemTypes) { super(parent, style); this.projects = projects; selectedQueryItem = initialQueryItem; this.itemTypes = itemTypes; activeProjectNames = activeProjects; Arrays.sort(activeProjectNames); if (activeProjectNames.length > 0) { /* * set up the tree control in this composite */ createUI(); } else { createNoProjectsUI(); } } public QueryItem getSelectedQueryItem() { return selectedQueryItem; } public void addQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.add(listener); } } public void removeQueryItemDoubleClickedListener(final QueryItemDoubleClickedListener listener) { synchronized (queryDoubleClickListeners) { queryDoubleClickListeners.remove(listener); } } public void addQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.add(listener); } } public void removeQueryItemSelectionListener(final QueryItemSelectionListener listener) { synchronized (querySelectionListeners) { querySelectionListeners.remove(listener); } } private void createUI() { setLayout(new FillLayout()); treeViewer = new TreeViewer(this, SWT.BORDER); treeViewer.setContentProvider(new ContentProvider(activeProjectNames)); treeViewer.setLabelProvider(new LabelProvider()); treeViewer.addDoubleClickListener(new DoubleClickListener(treeViewer, queryDoubleClickListeners)); treeViewer.addSelectionChangedListener(new SelectionChangedListener(querySelectionListeners)); addContextMenu(); treeViewer.setInput(projects); /* * set the initial selection if applicable */ if (selectedQueryItem != null) { treeViewer.setSelection(new StructuredSelection(selectedQueryItem), true); } } private void createNoProjectsUI() { setLayout(new FillLayout()); final Label label = new Label(this, SWT.WRAP); label.setText(Messages.getString("QueryItemTreeControl.NoTeamProjectsLabelText")); //$NON-NLS-1$ } private void addContextMenu() { final MenuManager menuMgr = new MenuManager("#PopUp"); //$NON-NLS-1$ final IAction copyToClipboardAction = new Action() { @Override public void run() { final IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); final QueryDefinition queryDefinition = (QueryDefinition) selection.getFirstElement(); UIHelpers.copyToClipboard(queryDefinition.getQueryText()); } }; copyToClipboardAction.setText(Messages.getString("QueryItemTreeControl.CopyWiqlToClipboard")); //$NON-NLS-1$ copyToClipboardAction.setEnabled(false); menuMgr.add(copyToClipboardAction); treeViewer.getControl().setMenu(menuMgr.createContextMenu(treeViewer.getControl())); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { final IStructuredSelection selection = (IStructuredSelection) event.getSelection(); final boolean enable = (selection.getFirstElement() instanceof QueryDefinition); copyToClipboardAction.setEnabled(enable); } }); } private class SelectionChangedListener implements ISelectionChangedListener { private final Set listeners; public SelectionChangedListener(final Set listeners) { this.listeners = listeners; } @Override public void selectionChanged(final SelectionChangedEvent event) { final Object selected = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selected instanceof QueryItem && itemTypes.contains(((QueryItem) selected).getType())) { selectedQueryItem = (QueryItem) selected; } else { selectedQueryItem = null; } synchronized (listeners) { for (final QueryItemSelectionListener listener : listeners) { listener.queryItemSelected(selectedQueryItem); } } } } private static class DoubleClickListener extends TreeViewerDoubleClickListener { private final Set listeners; public DoubleClickListener(final TreeViewer treeViewer, final Set listeners) { super(treeViewer); this.listeners = listeners; } @Override public void doubleClick(final DoubleClickEvent event) { super.doubleClick(event); final Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; synchronized (listeners) { for (final QueryItemDoubleClickedListener listener : listeners) { listener.queryItemDoubleClicked(queryDefinition); } } } } } private class ContentProvider extends TreeContentProvider { private final String[] activeProjectNames; public ContentProvider(final String[] activeProjectNames) { this.activeProjectNames = activeProjectNames; } @Override public Object getParent(final Object element) { if (element instanceof QueryHierarchy) { return null; } return ((QueryItem) element).getParent(); } @Override public Object[] getChildren(final Object parentElement) { final QueryItemType displayTypes = getDisplayTypes(); if (parentElement instanceof QueryFolder) { final List childList = new ArrayList(); final QueryItem[] children = ((QueryFolder) parentElement).getItems(); for (final QueryItem child : children) { if (displayTypes.contains(child.getType())) { childList.add(child); } } return childList.toArray(new QueryItem[childList.size()]); } return null; } @Override public boolean hasChildren(final Object element) { final QueryItemType displayTypes = getDisplayTypes(); if (element instanceof QueryFolder) { final QueryItem[] children = ((QueryFolder) element).getItems(); for (int i = 0; i < children.length; i++) { if (displayTypes.contains(children[i].getType())) { return true; } } } return false; } private QueryItemType getDisplayTypes() { if (itemTypes.contains(QueryItemType.QUERY_DEFINITION)) { return QueryItemType.ALL; } else if (itemTypes.contains(QueryItemType.QUERY_FOLDER)) { return QueryItemType.ALL_FOLDERS; } return itemTypes; } @Override public Object[] getElements(final Object inputElement) { final Project[] projects = (Project[]) inputElement; final List queryHierarchies = new ArrayList(); final Map availableProjects = new HashMap(); for (final Project project : projects) { availableProjects.put(project.getName(), project); } for (final String activeProjectName : activeProjectNames) { final Project project = availableProjects.get(activeProjectName); if (project != null) { queryHierarchies.add(project.getQueryHierarchy()); } } return queryHierarchies.toArray(new QueryHierarchy[queryHierarchies.size()]); } } private static class LabelProvider extends org.eclipse.jface.viewers.LabelProvider { private final Map definitionToQueryMap = new HashMap(); private final ImageHelper imageHelper = new ImageHelper(TFSCommonUIClientPlugin.PLUGIN_ID); public LabelProvider() { } @Override public Image getImage(final Object element) { if (element instanceof QueryHierarchy) { return imageHelper.getImage("images/common/team_project.gif"); //$NON-NLS-1$ } if (element instanceof QueryFolder) { final QueryFolder queryFolder = (QueryFolder) element; if (GUID.EMPTY.getGUIDString().replaceAll("-", "").equals(queryFolder.getParent().getID())) //$NON-NLS-1$ //$NON-NLS-2$ { // This is a top level "Team Queries" / "My Queries" folder if (queryFolder.isPersonal()) { return imageHelper.getImage("images/wit/query_group_my.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_group_team.gif"); //$NON-NLS-1$ } return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } if (element instanceof QueryDefinition) { final QueryDefinition queryDefinition = (QueryDefinition) element; StoredQuery query = definitionToQueryMap.get(queryDefinition); if (query == null) { query = new StoredQueryImpl( queryDefinition.getID(), queryDefinition.getName(), queryDefinition.getQueryText(), queryDefinition.isPersonal() ? QueryScope.PRIVATE : QueryScope.PUBLIC, queryDefinition.getProject().getID(), (ProjectImpl) queryDefinition.getProject(), queryDefinition.isDeleted(), queryDefinition.getProject().getWITContext()); definitionToQueryMap.put(queryDefinition, query); } if (QueryType.LIST.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_flat.gif"); //$NON-NLS-1$ } else if (QueryType.TREE.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_tree.gif"); //$NON-NLS-1$ } else if (QueryType.ONE_HOP.equals(queryDefinition.getQueryType())) { return imageHelper.getImage("images/wit/query_type_onehop.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query_type_flat_error.gif"); //$NON-NLS-1$ } return imageHelper.getImage("images/wit/query.gif"); //$NON-NLS-1$ } @Override public String getText(final Object element) { return ((QueryItem) element).getName(); } @Override public void dispose() { imageHelper.dispose(); } } } |
blob | blob, long method, data class | t | t | t | long method, data class | 0 | 1268 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/wit/controls/QueryItemTreeControl.java/#L52-L416 | 1 | 95 | 1268 | minor | |
| 581 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method, data class | t | t | t | data class | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 581 | 5786 | major | |
| 362 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Listener(clustered = false, sync = false) public class InfinispanAsyncLocalEventListener extends InfinispanSyncLocalEventListener { public InfinispanAsyncLocalEventListener(InfinispanConsumer consumer, Set eventTypes) { super(consumer, eventTypes); } } |
data class | data class | t | t | t | 0 | 3707 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanAsyncLocalEventListener.java/#L24-L29 | 1 | 362 | 3707 | major | ||
| 1200 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Code duplication (in the if statements for different subclasses of colWidth) 4. Inconsistent formatting (spacing, use of braces) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Code duplication (in the if statements for different subclasses of colWidth)4 Inconsistent formatting (spacing, use of braces) | t | f | t | use of braces) | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1200 | 10279 | minor | |
| 5399 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | blob, long method | t | t | t | long method | 0 | 15171 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L233896-L233981 | 1 | 5399 | 15171 | minor | |
| 1304 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10672 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 1304 | 10672 | minor | |
| 4484 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HeaderParser { private static final String DIRECTIVE_FILTER = "filter"; // NOI18N private final String headerName; private final Map parameters = new HashMap<>(); private final Map directives = new HashMap<>(); private final Map filterValue = new HashMap<>(); private final Feedback feedback; private String header; private int pos; private String directiveOrParameterName; private int contentStart; private String versionFilter; // static final ResourceBundle BUNDLE = // ResourceBundle.getBundle("org.graalvm.component.installer.persist.Bundle"); public HeaderParser(String headerName, String header, Feedback feedback) { this.headerName = headerName; this.feedback = feedback; if (header != null) { // trim whitespaces; this.header = header.trim(); } else { this.header = ""; } } private MetadataException metaEx(String key, Object... args) { return new MetadataException(headerName, feedback.l10n(key, args)); } public HeaderParser mustExist() throws MetadataException { if (header == null || header.isEmpty()) { throw metaEx("ERROR_HeaderMissing", headerName); } return this; } private static boolean isAlphaNum(char c) { return (c >= '0' && c <= '9') || // NOI18N (c >= 'A' && c <= 'Z') || // NOI18N (c >= 'a' && c <= 'z'); // NOI18N } private static boolean isToken(char c) { return isAlphaNum(c) || c == '_' || c == '-'; // NOI18N } private static boolean isExtended(char c) { return isToken(c) || c == '.'; } public boolean getBoolean(Boolean defValue) { if (pos >= header.length()) { if (defValue == null) { throw metaEx("ERROR_HeaderMissing", headerName); // NOI18N } return defValue; } else { String s = header.substring(pos).trim().toLowerCase(Locale.ENGLISH); switch (s) { case "true": // NOI18N return true; case "false": // NOI18N return false; } throw metaEx("ERROR_HeaderInvalid", headerName, s); // NOI18N } } public String getContents(String defValue) { if (pos >= header.length()) { return defValue; } else { return header.substring(pos).trim(); } } private void addFilterAttribute(String attrName, String value) { if (filterValue.put(attrName, value) != null) { throw metaErr("ERROR_DuplicateFilterAttribute"); } } private boolean isEmpty() { return pos >= header.length(); } public String parseSymbolicName() throws MetadataException { return parseNameOrNamespace(HeaderParser::isToken, "ERROR_MissingSymbolicName", "ERROR_InvalidSymbolicName", '.'); } private char next() { return pos < header.length() ? header.charAt(pos++) : 0; } private void advance() { pos++; } private char ch() { return isEmpty() ? 0 : header.charAt(pos); } private String returnCut() { String s = cut(); skipWhitespaces(); return s; } private void skipWhitespaces() { while (!isEmpty()) { if (!Character.isWhitespace(ch())) { contentStart = pos; return; } advance(); } contentStart = -1; } private void skipWithSemicolon() { skipWhitespaces(); if (ch() == ';') { advance(); } contentStart = -1; } private String cut() { return cut(0); } private String cut(int delim) { int e = pos - delim; return contentStart == -1 || contentStart >= e ? "" : header.substring(contentStart, e); // NOI18N } private void markContent() { contentStart = pos; } private String readExtendedParameter() throws MetadataException { skipWhitespaces(); while (!isEmpty()) { char c = next(); if (Character.isWhitespace(c)) { break; } if (!isExtended(c)) { throw metaEx("ERROR_InvalidParameterSyntax", directiveOrParameterName); } } String s = cut(); skipWithSemicolon(); return s; } private String readQuotedParameter() throws MetadataException { markContent(); while (!isEmpty()) { char c = next(); switch (c) { case '"': return cut(1); case '\n': case '\r': case 0: throw metaEx("ERROR_InvalidQuotedString"); case '\\': next(); break; } } throw metaEx("ERROR_InvalidQuotedString"); } private String parseArgument() throws MetadataException { skipWhitespaces(); char c = ch(); if (c == ';') { throw metaEx("ERROR_MissingArgument", directiveOrParameterName); } if (c == '"') { // NOI18N advance(); return readQuotedParameter(); } else { return readExtendedParameter(); } } private String parseNameOrNamespace(Predicate charAcceptor, String missingKeyName, String invalidKeyName, char compDelimiter) throws MetadataException { if (header == null || isEmpty()) { throw metaEx(missingKeyName); } skipWhitespaces(); boolean componentEmpty = true; while (!isEmpty()) { char c = ch(); if (c == ';') { String s = cut(); return s; } advance(); if (c == compDelimiter) { if (componentEmpty) { throw metaEx(invalidKeyName); } componentEmpty = true; continue; } if (Character.isWhitespace(c)) { break; } if (!charAcceptor.test(c)) { throw metaEx(invalidKeyName); } componentEmpty = false; } return returnCut(); } private String parseNamespace() throws MetadataException { return parseNameOrNamespace(HeaderParser::isExtended, "ERROR_MissingCapabilityName", "ERROR_InvalidCapabilityName", (char) 0); } /** * Parses version at the current position. */ public String version() throws MetadataException { int versionStart = -1; int partCount = 0; boolean partContents = false; if (isEmpty()) { throw metaErr("ERROR_InvalidVersion"); } boolean dash = false; while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (versionStart != -1) { break; } advance(); continue; } if (c == ';') { break; } advance(); if (c == '.') { if (++partCount > 3 || !partContents) { throw metaErr("ERROR_InvalidVersion"); } partContents = false; dash = false; continue; } if (partCount > 0 && partContents && c == '-') { dash = true; continue; } if (c >= '0' && c <= '9') { if (versionStart == -1) { versionStart = pos - 1; } } else { if (partCount < 1) { throw metaErr("ERROR_InvalidVersion"); } boolean err = false; if (partCount >= 3 || dash) { err = !isToken(c); } else { err = true; } if (err) { throw metaErr("ERROR_InvalidVersion"); } } partContents = true; } String v = cut(); skipWhitespaces(); if (!isEmpty() || !partContents) { throw metaErr("ERROR_InvalidVersion"); } return v; } private String readExtendedName() { skipWhitespaces(); while (!isEmpty()) { char c = ch(); if (isExtended(c)) { advance(); } else if (Character.isWhitespace(c) || c == ':' || c == '=') { break; } else { throw metaEx("ERROR_InvalidParameterName"); } } return returnCut(); } private void parseParameters() { while (!isEmpty()) { String paramOrDirectiveName = readExtendedName(); if (paramOrDirectiveName.isEmpty()) { throw metaEx("ERROR_InvalidParameterName"); } directiveOrParameterName = paramOrDirectiveName; char c = ch(); boolean dcolon = c == ':'; // NOI18N if (dcolon) { advance(); } c = next(); if (c != '=') { // NOI18N throw metaEx("ERROR_InvalidParameterSyntax", paramOrDirectiveName); } (dcolon ? directives : parameters).put(paramOrDirectiveName, parseArgument()); } } private void replaceInputText(String text) { this.header = text; this.pos = 0; } private MetadataException metaErr(String key, Object... args) throws MetadataException { throw metaEx(key, args); } private MetadataException filterError() throws MetadataException { throw metaErr("ERROR_InvalidFilterSpecification"); } private void parseFilterConjunction() { skipWhitespaces(); char c = next(); while (c == '(') { parseFilterContent(); c = next(); } if (c != ')') { throw filterError(); } } private void parseFilterClause() { skipWhitespaces(); int lastPos = -1; W: while (!isEmpty()) { char c = ch(); if (Character.isWhitespace(c)) { if (lastPos == -1) { lastPos = pos; } continue; } switch (c) { case '=': case '<': case '>': case '~': case '(': case ')': break W; } lastPos = -1; advance(); } String attributeName = returnCut(); char c = next(); if (c != '=') { throw metaErr("ERROR_UnsupportedFilterOperation"); } c = ch(); if (c == '*') { throw metaErr("ERROR_UnsupportedFilterOperation"); } markContent(); while (!isEmpty()) { c = next(); if (c == ')') { addFilterAttribute(attributeName, cut(1)); skipWhitespaces(); return; } switch (c) { case '\\': c = next(); if (c == 0) { throw filterError(); } break; case '*': throw metaErr("ERROR_UnsupportedFilterOperation"); case '(': case '<': case '>': case '~': case '=': throw filterError(); } } throw filterError(); } private void parseFilterContent() { skipWhitespaces(); char o = ch(); if (o == '&') { advance(); parseFilterConjunction(); } else if (isExtended(o)) { parseFilterClause(); } else { throw metaErr("ERROR_InvalidFilterSpecification"); } } private void parseFilterSpecification() { skipWhitespaces(); if (isEmpty()) { throw filterError(); } char c = next(); if (c == '(') { parseFilterContent(); skipWhitespaces(); if (!isEmpty()) { throw metaErr("ERROR_InvalidFilterSpecification"); } } else { throw filterError(); } } /** * Parses required capabilities string. * * org.graalvm; filter:="(&(graalvm_version=0.32)(os_name=linux)(os_arch=amd64))" * * @return graal capabilities * @throws MetadataException */ public Map parseRequiredCapabilities() { String namespace = parseNamespace(); char c = next(); if (c != ';' && c != 0) { throw metaErr("ERROR_InvalidFilterSpecification"); } if (!BundleConstants.GRAALVM_CAPABILITY.equals(namespace)) { // unsupported capability throw new DependencyException(namespace, null, null, feedback.l10n("ERROR_UnknownCapability")); } parseParameters(); if (!parameters.isEmpty()) { throw metaErr("ERROR_UnsupportedParameters"); } versionFilter = directives.remove(DIRECTIVE_FILTER); if (!directives.isEmpty()) { throw metaErr("ERROR_UnsupportedDirectives"); } if (versionFilter == null) { throw metaErr("ERROR_MissingVersionFilter"); } // replace the input text, the rest of header will be ignored replaceInputText(versionFilter); parseFilterSpecification(); return filterValue; } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 11873 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/vm/src/org.graalvm.component.installer/src/org/graalvm/component/installer/persist/HeaderParser.java/#L39-L528 | 1 | 4484 | 11873 | major | |
| 2054 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class | t | t | t | 0 | 12922 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 2054 | 12922 | minor | ||
| 224 | { "message": "YES I found bad smells", "bad smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 1 | 224 | 2418 | minor | |
| 2363 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | long method, data class | t | t | t | long method | 0 | 14254 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 2363 | 14254 | critical | |
| 2640 | { "output": "YES, I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 15143 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2640 | 15143 | major | ||
| 288 | YES I found bad smells. the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public CreateBudgetDetails build() { CreateBudgetDetails __instance__ = new CreateBudgetDetails( compartmentId, targetCompartmentId, displayName, description, amount, resetPeriod, freeformTags, definedTags); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 3061 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-budget/src/main/java/com/oracle/bmc/budget/model/CreateBudgetDetails.java/#L103-L116 | 2 | 288 | 3061 | critical | |
| 474 | {"message": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean supportsParameter(MethodParameter parameter) { if (!super.supportsParameter(parameter)) { return false; } Class type = parameter.getParameterType(); if (!type.isInterface()) { return false; } // Annotated parameter if (parameter.getParameterAnnotation(ProjectedPayload.class) != null) { return true; } // Annotated type if (AnnotatedElementUtils.findMergedAnnotation(type, ProjectedPayload.class) != null) { return true; } // Fallback for only user defined interfaces String packageName = ClassUtils.getPackageName(type); return !IGNORED_PACKAGES.stream().anyMatch(it -> packageName.startsWith(it)); } |
long method | 1. long method | t | t | f | long method | 0 | 4578 | https://github.com/spring-projects/spring-data-commons/blob/48c9297118e18273a0a3dfe3cf2f9a8ffd8fdca7/src/main/java/org/springframework/data/web/ProxyingHandlerMethodArgumentResolver.java/#L88-L115 | 1 | 474 | 4578 | minor | |
| 3075 | {"response": "YES I found bad smells", "bad smells": ["Feature Envy", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public InstrumentationFacility getInstrumentationFacility() { return getRootContext().getInstrumentationFacility(); } |
feature envy | feature envy, long method | t | t | t | long method | 0 | 3714 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-core/src/main/java/org/apache/uima/impl/ChildUimaContext_impl.java/#L101-L103 | 1 | 3075 | 3714 | minor | |
| 1771 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Component public class VirtualMachineEntityImpl implements VirtualMachineEntity { @Inject private VMEntityManager manager; private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } public void init(String vmId) { this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public void init(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks) { init(vmId); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { this.manager = manager; this.vmEntityVO = this.manager.loadVirtualMachine(vmId); } public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { this(vmId, manager); this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); manager.saveVirtualMachine(vmEntityVO); } @Override public String getUuid() { return vmEntityVO.getUuid(); } @Override public long getId() { return vmEntityVO.getId(); } @Override public String getCurrentState() { // TODO Auto-generated method stub return null; } @Override public String getDesiredState() { // TODO Auto-generated method stub return null; } @Override public Date getCreatedTime() { return vmEntityVO.getCreated(); } @Override public Date getLastUpdatedTime() { return vmEntityVO.getUpdateTime(); } @Override public String getOwner() { // TODO Auto-generated method stub return null; } @Override public Map getDetails() { return vmEntityVO.getDetails(); } @Override public void addDetail(String name, String value) { vmEntityVO.setDetail(name, value); } @Override public void delDetail(String name, String value) { // TODO Auto-generated method stub } @Override public void updateDetail(String name, String value) { // TODO Auto-generated method stub } @Override public List getApplicableActions() { // TODO Auto-generated method stub return null; } @Override public List listVolumeIds() { // TODO Auto-generated method stub return null; } @Override public List listVolumes() { // TODO Auto-generated method stub return null; } @Override public List listNicUuids() { // TODO Auto-generated method stub return null; } @Override public List listNics() { // TODO Auto-generated method stub return null; } @Override public TemplateEntity getTemplate() { // TODO Auto-generated method stub return null; } @Override public List listTags() { // TODO Auto-generated method stub return null; } @Override public void addTag() { // TODO Auto-generated method stub } @Override public void delTag() { // TODO Auto-generated method stub } @Override public String reserve(DeploymentPlanner plannerToUse, DeploymentPlan plan, ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); } @Override public void migrateTo(String reservationId, String caller) { // TODO Auto-generated method stub } @Override public void deploy(String reservationId, String caller, Map params, boolean deployOnGivenHost) throws InsufficientCapacityException, ResourceUnavailableException { manager.deployVirtualMachine(reservationId, this.vmEntityVO, caller, params, deployOnGivenHost); } @Override public boolean stop(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachine(this.vmEntityVO, caller); } @Override public boolean stopForced(String caller) throws ResourceUnavailableException { return manager.stopvirtualmachineforced(this.vmEntityVO, caller); } @Override public void cleanup() { // TODO Auto-generated method stub } @Override public boolean destroy(String caller, boolean expunge) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { return manager.destroyVirtualMachine(this.vmEntityVO, caller, expunge); } @Override public VirtualMachineEntity duplicate(String externalId) { // TODO Auto-generated method stub return null; } @Override public SnapshotEntity takeSnapshotOf() { // TODO Auto-generated method stub return null; } @Override public void attach(VolumeEntity volume, short deviceId) { // TODO Auto-generated method stub } @Override public void detach(VolumeEntity volume) { // TODO Auto-generated method stub } @Override public void connectTo(NetworkEntity network, short nicId) { // TODO Auto-generated method stub } @Override public void disconnectFrom(NetworkEntity netowrk, short nicId) { // TODO Auto-generated method stub } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 11920 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/engine/orchestration/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java/#L39-L272 | 1 | 1771 | 11920 | minor | |
| 3806 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | long method | t | t | t | 0 | 9657 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3806 | 9657 | major | ||
| 650 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6383 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 650 | 6383 | minor | ||
| 1991 | YES, I found bad smells The bad smells are: 1. Duplicated code 2. Long method 3. Feature envy 4. Magic numbers (specific values used without explanation) 5. Primitive obsession (using basic data types instead of creating custom classes for data) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Duplicated code2 Long method3 Feature envy4 Magic numbers (specific values used without explanation)5 Primitive obsession (using basic data types instead of creating custom classes for data) | t | f | t | 0 | 12682 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1991 | 12682 | major | ||
| 3334 | {"message": "YES I found bad smells, the bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | 1. long method | t | t | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 1 | 3334 | 6247 | critical | ||
| 1165 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReloadingFileBasedConfigurationBuilder extends FileBasedConfigurationBuilder implements ReloadingControllerSupport { /** The default factory for creating reloading detector objects. */ private static final ReloadingDetectorFactory DEFAULT_DETECTOR_FACTORY = new DefaultReloadingDetectorFactory(); /** The reloading controller associated with this object. */ private final ReloadingController reloadingController; /** * The reloading detector which does the actual reload check for the current * result object. A new instance is created whenever a new result object * (and thus a new current file handler) becomes available. The field must * be volatile because it is accessed by the reloading controller probably * from within another thread. */ private volatile ReloadingDetector resultReloadingDetector; /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params) { super(resCls, params); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class and sets * initialization parameters and the allowFailOnInit flag. * * @param resCls the result class (must not be null * @param params a map with initialization parameters * @param allowFailOnInit the allowFailOnInit flag * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls, final Map params, final boolean allowFailOnInit) { super(resCls, params, allowFailOnInit); reloadingController = createReloadingController(); } /** * Creates a new instance of {@code ReloadingFileBasedConfigurationBuilder} * which produces result objects of the specified class. * * @param resCls the result class (must not be null * @throws IllegalArgumentException if the result class is null */ public ReloadingFileBasedConfigurationBuilder(final Class resCls) { super(resCls); reloadingController = createReloadingController(); } /** * Returns the {@code ReloadingController} associated with this builder. * This controller is directly created. However, it becomes active (i.e. * associated with a meaningful reloading detector) not before a result * object was created. * * @return the {@code ReloadingController} */ @Override public ReloadingController getReloadingController() { return reloadingController; } /** * {@inheritDoc} This method is overridden here to change the result type. */ @Override public ReloadingFileBasedConfigurationBuilder configure( final BuilderParameters... params) { super.configure(params); return this; } /** * Creates a {@code ReloadingDetector} which monitors the passed in * {@code FileHandler}. This method is called each time a new result object * is created with the current {@code FileHandler}. This implementation * checks whether a {@code ReloadingDetectorFactory} is specified in the * current parameters. If this is the case, it is invoked. Otherwise, a * default factory is used to create a {@code FileHandlerReloadingDetector} * object. Note: This method is called from a synchronized block. * * @param handler the current {@code FileHandler} * @param fbparams the object with parameters related to file-based builders * @return a {@code ReloadingDetector} for this {@code FileHandler} * @throws ConfigurationException if an error occurs */ protected ReloadingDetector createReloadingDetector(final FileHandler handler, final FileBasedBuilderParametersImpl fbparams) throws ConfigurationException { return fetchDetectorFactory(fbparams).createReloadingDetector(handler, fbparams); } /** * {@inheritDoc} This implementation also takes care that a new * {@code ReloadingDetector} for the new current {@code FileHandler} is * created. Also, the reloading controller's reloading state has to be * reset; after the creation of a new result object changes in the * underlying configuration source have to be monitored again. */ @Override protected void initFileHandler(final FileHandler handler) throws ConfigurationException { super.initFileHandler(handler); resultReloadingDetector = createReloadingDetector(handler, FileBasedBuilderParametersImpl.fromParameters( getParameters(), true)); } /** * Creates the {@code ReloadingController} associated with this object. The * controller is assigned a specialized reloading detector which delegates * to the detector for the current result object. ( * {@code FileHandlerReloadingDetector} does not support changing the file * handler, and {@code ReloadingController} does not support changing the * reloading detector; therefore, this level of indirection is needed to * change the monitored file dynamically.) * * @return the new {@code ReloadingController} */ private ReloadingController createReloadingController() { final ReloadingDetector ctrlDetector = createReloadingDetectorForController(); final ReloadingController ctrl = new ReloadingController(ctrlDetector); connectToReloadingController(ctrl); return ctrl; } /** * Creates a {@code ReloadingDetector} wrapper to be passed to the * associated {@code ReloadingController}. This detector wrapper simply * delegates to the current {@code ReloadingDetector} if it is available. * * @return the wrapper {@code ReloadingDetector} */ private ReloadingDetector createReloadingDetectorForController() { return new ReloadingDetector() { @Override public void reloadingPerformed() { final ReloadingDetector detector = resultReloadingDetector; if (detector != null) { detector.reloadingPerformed(); } } @Override public boolean isReloadingRequired() { final ReloadingDetector detector = resultReloadingDetector; return (detector != null) && detector.isReloadingRequired(); } }; } /** * Returns a {@code ReloadingDetectorFactory} either from the passed in * parameters or a default factory. * * @param params the current parameters object * @return the {@code ReloadingDetectorFactory} to be used */ private static ReloadingDetectorFactory fetchDetectorFactory( final FileBasedBuilderParametersImpl params) { final ReloadingDetectorFactory factory = params.getReloadingDetectorFactory(); return (factory != null) ? factory : DEFAULT_DETECTOR_FACTORY; } } |
data class | long method, data class | t | t | t | long method | 0 | 10183 | https://github.com/apache/commons-configuration/blob/34357e075d63c3634310878636f9498847badcab/src/main/java/org/apache/commons/configuration2/builder/ReloadingFileBasedConfigurationBuilder.java/#L62-L255 | 1 | 1165 | 10183 | minor | |
| 13 | {"message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public JsonGenerator(LogIterator iter) { servers = new HashSet(); Pattern stateChangeP = Pattern.compile("- (LOOKING|FOLLOWING|LEADING)"); Pattern newElectionP = Pattern.compile("New election. My id = (\\d+), Proposed zxid = (\\d+)"); Pattern receivedProposalP = Pattern.compile("Notification: (\\d+) \\(n.leader\\), (\\d+) \\(n.zxid\\), (\\d+) \\(n.round\\), .+ \\(n.state\\), (\\d+) \\(n.sid\\), .+ \\(my state\\)"); Pattern exceptionP = Pattern.compile("xception"); root = new JSONObject(); Matcher m = null; JSONArray events = new JSONArray(); root.put("events", events); long starttime = Long.MAX_VALUE; long endtime = 0; int leader = 0; long curEpoch = 0; boolean newEpoch = false; while (iter.hasNext()) { LogEntry ent = iter.next(); if (ent.getTimestamp() < starttime) { starttime = ent.getTimestamp(); } if (ent.getTimestamp() > endtime) { endtime = ent.getTimestamp(); } if (ent.getType() == LogEntry.Type.TXN) { events.add(txnEntry((TransactionEntry)ent)); } else { Log4JEntry e = (Log4JEntry)ent; servers.add(e.getNode()); if ((m = stateChangeP.matcher(e.getEntry())).find()) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", e.getNode()); stateChange.put("state", m.group(1)); events.add(stateChange); if (m.group(1).equals("LEADING")) { leader = e.getNode(); } } else if ((m = newElectionP.matcher(e.getEntry())).find()) { Iterator iterator = servers.iterator(); long zxid = Long.valueOf(m.group(2)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } while (iterator.hasNext()) { int dst = iterator.next(); if (dst != e.getNode()) { JSONObject msg = new JSONObject(); msg.put("type", "postmessage"); msg.put("src", e.getNode()); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", m.group(2)); msg.put("count", count); msg.put("epoch", epoch); events.add(msg); } } } else if ((m = receivedProposalP.matcher(e.getEntry())).find()) { // Pattern.compile("Notification: \\d+, (\\d+), (\\d+), \\d+, [^,]*, [^,]*, (\\d+)");//, LOOKING, LOOKING, 2 int src = Integer.valueOf(m.group(4)); long zxid = Long.valueOf(m.group(2)); int dst = e.getNode(); long epoch2 = Long.valueOf(m.group(3)); int count = (int)zxid;// & 0xFFFFFFFFL; int epoch = (int)Long.rotateRight(zxid, 32);// >> 32; if (leader != 0 && epoch > curEpoch) { JSONObject stateChange = new JSONObject(); stateChange.put("type", "stateChange"); stateChange.put("time", e.getTimestamp()); stateChange.put("server", leader); stateChange.put("state", "INIT"); events.add(stateChange); leader = 0; } if (src != dst) { JSONObject msg = new JSONObject(); msg.put("type", "delivermessage"); msg.put("src", src); msg.put("dst", dst); msg.put("time", e.getTimestamp()); msg.put("zxid", zxid); msg.put("epoch", epoch); msg.put("count", count); msg.put("epoch2", epoch2); events.add(msg); } } else if ((m = exceptionP.matcher(e.getEntry())).find()) { JSONObject ex = new JSONObject(); ex.put("type", "exception"); ex.put("server", e.getNode()); ex.put("time", e.getTimestamp()); ex.put("text", e.getEntry()); events.add(ex); } } JSONObject ex = new JSONObject(); ex.put("type", "text"); ex.put("time", ent.getTimestamp()); String txt = ent.toString(); ex.put("text", txt); events.add(ex); } // System.out.println("pending messages: "+pendingMessages.size()); root.put("starttime", starttime); root.put("endtime", endtime); JSONArray serversarray = new JSONArray(); root.put("servers", serversarray); Iterator iterator = servers.iterator(); while (iterator.hasNext()) { serversarray.add(iterator.next()); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 622 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/java/org/apache/zookeeper/graph/JsonGenerator.java/#L75-L213 | 2 | 13 | 622 | major | |
| 1777 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
blob | blob | t | t | t | 0 | 11957 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 1777 | 11957 | minor | ||
| 715 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 6821 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 715 | 6821 | major | |
| 2575 | {"message": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | 1. long method | t | t | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 2575 | 14915 | minor | ||
| 647 | YES I found bad smells the bad smells are: 1. Feature envy (currentIterator.reset() being called on a different object without any clear ownership or reason) 2. Long method (the method contains multiple operations and variable assignments) 3. Conditional complexity (if statement and compareAndSet() method in the same line) 4. Boolean trap (reset() method is called even if the if statement is not satisfied, leading to unnecessary operations) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void reset() { RepeatableIteratorWrapper changedIterator = this.changedIterator; if (changedIterator != null) { currentIterator = changedIterator; changedIteratorFieldUpdater.compareAndSet(this, changedIterator, null); } currentIterator.reset(); } |
feature envy | Feature envy (currentIteratorreset() being called on a different object without any clear ownership or reason)2 Long method (the method contains multiple operations and variable assignments)3 Conditional complexity (if statement and compareAndSet() method in the same line)4 Boolean trap (reset() method is called even if the if statement is not satisfied, leading to unnecessary operations) | t | f | t | leading to unnecessary operations) | 0 | 6374 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/UpdatableIterator.java/#L58-L66 | 2 | 647 | 6374 | minor | |
| 451 | {"response": "YES I found bad smells the bad smells are: 1. Long Method, 2. Blob"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RemoteWasbDelegationTokenManager implements WasbDelegationTokenManager { /** * Configuration parameter name expected in the configuration * object to provide the url of the delegation token service to fetch the delegation tokens. */ public static final String KEY_DELEGATION_TOKEN_SERVICE_URLS = "fs.azure.delegation.token.service.urls"; /** * Configuration key to enable http retry policy for delegation token service calls. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY = "fs.azure.delegationtokenservice.http.retry.policy.enabled"; /** * Configuration key for delegation token service http retry policy spec. */ public static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY = "fs.azure.delegationtokenservice.http.retry.policy.spec"; /** * Default remote delegation token manager endpoint. */ private static final String DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT = "/tokenmanager/v1"; /** * Default for delegation token service http retry policy spec. */ private static final String DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT = "10,3,100,2"; private static final boolean DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT = true; private static final Text WASB_DT_SERVICE_NAME = new Text("WASB_DT_SERVICE"); /** * Query parameter value for Getting delegation token http request */ private static final String GET_DELEGATION_TOKEN_OP = "GETDELEGATIONTOKEN"; /** * Query parameter value for renewing delegation token http request */ private static final String RENEW_DELEGATION_TOKEN_OP = "RENEWDELEGATIONTOKEN"; /** * Query parameter value for canceling the delegation token http request */ private static final String CANCEL_DELEGATION_TOKEN_OP = "CANCELDELEGATIONTOKEN"; /** * op parameter to represent the operation. */ private static final String OP_PARAM_KEY_NAME = "op"; /** * renewer parameter to represent the renewer of the delegation token. */ private static final String RENEWER_PARAM_KEY_NAME = "renewer"; /** * service parameter to represent the service which returns delegation tokens. */ private static final String SERVICE_PARAM_KEY_NAME = "service"; /** * token parameter to represent the delegation token. */ private static final String TOKEN_PARAM_KEY_NAME = "token"; private WasbRemoteCallHelper remoteCallHelper; private String[] dtServiceUrls; private boolean isSpnegoTokenCacheEnabled; public RemoteWasbDelegationTokenManager(Configuration conf) throws IOException { RetryPolicy retryPolicy = RetryUtils.getMultipleLinearRandomRetry(conf, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY, DT_MANAGER_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT); this.isSpnegoTokenCacheEnabled = conf.getBoolean(Constants.AZURE_ENABLE_SPNEGO_TOKEN_CACHE, true); remoteCallHelper = new SecureWasbRemoteCallHelper(retryPolicy, true, isSpnegoTokenCacheEnabled); this.dtServiceUrls = conf.getTrimmedStrings(KEY_DELEGATION_TOKEN_SERVICE_URLS); if (this.dtServiceUrls == null || this.dtServiceUrls.length <= 0) { throw new IOException( KEY_DELEGATION_TOKEN_SERVICE_URLS + " config not set" + " in configuration."); } } @Override public Token getDelegationToken( String renewer) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, GET_DELEGATION_TOKEN_OP) .addParameter(RENEWER_PARAM_KEY_NAME, renewer) .addParameter(SERVICE_PARAM_KEY_NAME, WASB_DT_SERVICE_NAME.toString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpGet.METHOD_NAME); return TokenUtils.toDelegationToken(JsonUtils.parse(responseBody)); } @Override public long renewDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, RENEW_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); String responseBody = remoteCallHelper .makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); Map parsedResp = JsonUtils.parse(responseBody); return ((Number) parsedResp.get("long")).longValue(); } @Override public void cancelDelegationToken(Token token) throws IOException { URIBuilder uriBuilder = new URIBuilder().setPath(DEFAULT_DELEGATION_TOKEN_MANAGER_ENDPOINT) .addParameter(OP_PARAM_KEY_NAME, CANCEL_DELEGATION_TOKEN_OP) .addParameter(TOKEN_PARAM_KEY_NAME, token.encodeToUrlString()); remoteCallHelper.makeRemoteRequest(dtServiceUrls, uriBuilder.getPath(), uriBuilder.getQueryParams(), HttpPut.METHOD_NAME); } } |
blob | 1. long method, 2. blob | t | t | f | 1. long method | blob | 0 | 4407 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/security/RemoteWasbDelegationTokenManager.java/#L39-L169 | 1 | 451 | 4407 | minor |
| 1897 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Implementation(minSdk = LOLLIPOP) @HiddenApi protected static void nativeGetPointerCoords( long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) { NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr); int pointerCount = event.getPointerCount(); validatePointerIndex(pointerIndex, pointerCount); validatePointerCoords(outPointerCoordsObj); NativeInput.PointerCoords rawPointerCoords; if (historyPos == HISTORY_CURRENT) { rawPointerCoords = event.getRawPointerCoords(pointerIndex); } else { int historySize = event.getHistorySize(); validateHistoryPos(historyPos, historySize); rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos); } pointerCoordsFromNative( rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj); } |
long method | long method | t | t | t | 0 | 12341 | https://github.com/robolectric/robolectric/blob/525bfcfc0e0ed1653ad57341b564c6857e11dc50/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java/#L386-L405 | 1 | 1897 | 12341 | minor | ||
| 1136 | YES I found bad smells the bad smells are: 1. long method, 2. feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method, 2 feature envy | t | f | t | 2. feature envy | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1136 | 10058 | minor | |
| 683 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ThreadSafe public final class ServiceLocation { private final String location; private final String name; ServiceLocation(Element serviceLocationElement, String location) throws ServiceConfigException { String name = serviceLocationElement.getAttribute("name").intern(); if (name.isEmpty()) { throw new ServiceConfigException(" element name attribute is empty"); } this.name = name; if (location.isEmpty()) { throw new ServiceConfigException(" element location attribute is empty"); } this.location = location; } public String getLocation() { return location; } public String getName() { return name; } } |
data class | data class | t | t | t | 0 | 6610 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/framework/service/src/main/java/org/apache/ofbiz/service/config/model/ServiceLocation.java/#L28-L53 | 1 | 683 | 6610 | minor | ||
| 1626 | {"response":"YES I found bad smells","the bad smells are":["Long method","Deprecated field","Low cohesion","Feature envy","Long parameter list","Data class","Large class","Message chains","Inappropriate intimacy","Data clumps","Long class"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; /** * Specifies the path and filename to save the Checkstyle output. The format * of the output file is determined by the outputFileFormat * parameter. */ @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) private String outputFileFormat; /** * Fail the build on a violation. The goal checks for the violations * after logging them (if {@link #logViolationsToConsole} is {@code true}). * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) private boolean failOnViolation; /** * The maximum number of allowed violations. The execution fails only if the * number of violations is above this limit. * * @since 2.3 */ @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) private int maxAllowedViolations; /** * The lowest severity level that is considered a violation. * Valid values are "error", "warning" and "info". * * @since 2.2 */ @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) private String violationSeverity = "error"; /** * Violations to ignore. This is a comma-separated list, each value being either * a rule name, a rule category or a java package name of rule class. * * @since 2.13 */ @Parameter( property = "checkstyle.violation.ignore" ) private String violationIgnore; /** * Skip entire check. * * @since 2.2 */ @Parameter( property = "checkstyle.skip", defaultValue = "false" ) private boolean skip; /** * Skip Checkstyle execution will only scan the outputFile. * * @since 2.5 */ @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) private boolean skipExec; /** * Output the detected violations to the console. * * @since 2.3 */ @Parameter( property = "checkstyle.console", defaultValue = "true" ) private boolean logViolationsToConsole; /** * Specifies the location of the resources to be used for Checkstyle. * * @since 2.11 */ @Parameter( defaultValue = "${project.resources}", readonly = true ) protected List resources; /** * Specifies the location of the test resources to be used for Checkstyle. * * @since 2.16 */ @Parameter( defaultValue = "${project.testResources}", readonly = true ) protected List testResources; /** * * Specifies the location of the XML configuration to use. * * Potential values are a filesystem path, a URL, or a classpath resource. * This parameter expects that the contents of the location conform to the * xml format (Checkstyle Checker * module) configuration of rulesets. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the configuration is copied into the * ${project.build.directory}/checkstyle-configuration.xml * file before being passed to Checkstyle as a configuration. * * There are 2 predefined rulesets. * * sun_checks.xml: Sun Checks. * google_checks.xml: Google Checks. * * * @since 2.5 */ @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) private String configLocation; /** * * Specifies the location of the properties file. * * This parameter is resolved as URL, File then resource. If successfully * resolved, the contents of the properties location is copied into the * ${project.build.directory}/checkstyle-checker.properties * file before being passed to Checkstyle for loading. * * The contents of the propertiesLocation will be made * available to Checkstyle for specifying values for parameters within the * xml configuration (specified in the configLocation * parameter). * * @since 2.5 */ @Parameter( property = "checkstyle.properties.location" ) private String propertiesLocation; /** * Allows for specifying raw property expansion information. */ @Parameter private String propertyExpansion; /** * * Specifies the location of the License file (a.k.a. the header file) that * can be used by Checkstyle to verify that source code has the correct * license header. * * You need to use ${checkstyle.header.file} in your Checkstyle xml * configuration to reference the name of this header file. * * For instance: * * <module name="RegexpHeader"> * <property name="headerFile" value="${checkstyle.header.file}"/> * </module> * * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) private String cacheFile; /** * The key to be used in the properties for the suppressions file. * * @since 2.1 */ @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) private String suppressionsFileExpression; /** * * Specifies the location of the suppressions XML file to use. * * This parameter is resolved as resource, URL, then file. If successfully * resolved, the contents of the suppressions XML is copied into the * ${project.build.directory}/checkstyle-suppressions.xml file * before being passed to Checkstyle for loading. * * See suppressionsFileExpression for the property that will * be made available to your Checkstyle configuration. * * @since 2.0-beta-2 */ @Parameter( property = "checkstyle.suppressions.location" ) private String suppressionsLocation; /** * The file encoding to use when reading the source files. If the property project.build.sourceEncoding * is not set, the platform default encoding is used. Note: This parameter always overrides the * property charset from Checkstyle's TreeWalker module. * * @since 2.2 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String encoding; /** * @since 2.5 */ @Component( role = CheckstyleExecutor.class, hint = "default" ) protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) private boolean consoleOutput; /** * The Maven Project Object. */ @Parameter ( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * The Plugin Descriptor */ @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) private PluginDescriptor plugin; /** * If null, the Checkstyle plugin will display violations on stdout. * Otherwise, a text file will be created with the violations. */ @Parameter private File useFile; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ @Parameter( property = "checkstyle.excludes" ) private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) private String includes; /** * Specifies the names filter of the files to be excluded for * Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceExcludes" ) private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) private String resourceIncludes; /** * If this is true, and Checkstyle reported any violations or errors, * the build fails immediately after running Checkstyle, before checking the log * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ @Parameter( defaultValue = "false" ) private boolean failsOnError; /** * Specifies the location of the test source directory to be used for Checkstyle. * * @since 2.2 * @deprecated instead use {@link #testSourceDirectories}. For version 3.0.0, this parameter is only defined to * break the build if you use it! */ @Deprecated @Parameter private File testSourceDirectory; /** * Specifies the location of the test source directories to be used for Checkstyle. * Default value is ${project.testCompileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.testCompileSourceRoots' is done manually because of MNG-5440 @Parameter private List testSourceDirectories; /** * Include or not the test source directory to be used for Checkstyle. * * @since 2.2 */ @Parameter( defaultValue = "false" ) private boolean includeTestSourceDirectory; /** * Specifies the location of the source directory to be used for Checkstyle. * * @deprecated instead use {@link #sourceDirectories}. For version 3.0.0, this parameter is only defined to break * the build if you use it! */ @Deprecated @Parameter private File sourceDirectory; /** * Specifies the location of the source directories to be used for Checkstyle. * Default value is ${project.compileSourceRoots}. * @since 2.13 */ // Compatibility with all Maven 3: default of 'project.compileSourceRoots' is done manually because of MNG-5440 @Parameter private List sourceDirectories; /** * Whether to apply Checkstyle to resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) private boolean includeTestResources = true; /** * By using this property, you can specify the whole Checkstyle rules * inline directly inside this pom. * * * <plugin> * ... * <configuration> * <checkstyleRules> * <module name="Checker"> * <module name="FileTabCharacter"> * <property name="eachLine" value="true" /> * </module> * <module name="TreeWalker"> * <module name="EmptyBlock"/> * </module> * </module> * </checkstyleRules> * </configuration> * ... * * * @since 2.12 */ @Parameter private PlexusConfiguration checkstyleRules; /** * Dump file for inlined Checkstyle rules. */ @Parameter( property = "checkstyle.output.rules.file", defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ @Parameter( defaultValue = "\n" + "\n" ) private String checkstyleRulesHeader; /** * Specifies whether modules with a configured severity of ignore should be omitted during Checkstyle * invocation. * * @since 3.0.0 */ @Parameter( defaultValue = "false" ) private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; private File outputXmlFile; /** {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); if ( skip ) { return; } outputXmlFile = outputFile; if ( !skipExec ) { if ( checkstyleRules != null ) { if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) { throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " + "a configLocation" ); } if ( checkstyleRules.getChildCount() > 1 ) { throw new MojoExecutionException( "Currently only one root module is supported" ); } PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); try { FileUtils.forceMkdir( rulesFiles.getParentFile() ); FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); } catch ( final IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } configLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) .setResourceIncludes( resourceIncludes ) .setResourceExcludes( resourceExcludes ) .setIncludeResources( includeResources ) .setIncludeTestResources( includeTestResources ) .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) .setProject( project ).setSourceDirectories( getSourceDirectories() ) .setResources( resources ).setTestResources( testResources ) .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation ) .setConfigurationArtifacts( collectArtifacts( "config" ) ) .setPropertyExpansion( propertyExpansion ) .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) .setEncoding( encoding ).setPropertiesLocation( propertiesLocation ) .setOmitIgnoredModules( omitIgnoredModules ); checkstyleExecutor.executeCheckstyle( request ); } catch ( CheckstyleException e ) { throw new MojoExecutionException( "Failed during checkstyle configuration", e ); } catch ( CheckstyleExecutorException e ) { throw new MojoExecutionException( "Failed during checkstyle execution", e ); } finally { //be sure to restore original context classloader Thread.currentThread().setContextClassLoader( currentClassLoader ); } } if ( !"xml".equals( outputFileFormat ) && skipExec ) { throw new MojoExecutionException( "Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec." ); } if ( !outputXmlFile.exists() ) { getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); return; } try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) { XmlPullParser xpp = new MXParser(); xpp.setInput( reader ); int violations = countViolations( xpp ); if ( violations > maxAllowedViolations ) { if ( failOnViolation ) { String msg = "You have " + violations + " Checkstyle violation" + ( ( violations > 1 ) ? "s" : "" ) + "."; if ( maxAllowedViolations > 0 ) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } throw new MojoFailureException( msg ); } getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); } } catch ( IOException | XmlPullParserException e ) { throw new MojoExecutionException( "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e ); } } private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) throws MojoFailureException { if ( parameter != null ) { throw new MojoFailureException( "You are using '" + name + "' which has been removed" + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); } } private int countViolations( XmlPullParser xpp ) throws XmlPullParserException, IOException { int count = 0; int ignoreCount = 0; List ignores = violationIgnore == null ? Collections.emptyList() : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) { if ( eventType != XmlPullParser.START_TAG ) { continue; } else if ( "file".equals( xpp.getName() ) ) { file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); //file = file.substring( file.lastIndexOf( File.separatorChar ) + 1 ); } else if ( "error".equals( xpp.getName() ) ) { String severity = xpp.getAttributeValue( "", "severity" ); if ( !isViolation( severity ) ) { continue; } String source = xpp.getAttributeValue( "", "source" ); if ( ignore( ignores, source ) ) { ignoreCount++; } else { count++; if ( logViolationsToConsole ) { String line = xpp.getAttributeValue( "", "line" ); String column = xpp.getAttributeValue( "", "column" ); String message = xpp.getAttributeValue( "", "message" ); String rule = RuleUtil.getName( source ); String category = RuleUtil.getCategory( source ); log( severity, file + ":[" + line + ( ( column == null ) ? "" : ( ',' + column ) ) + "] (" + category + ") " + rule + ": " + message ); } } } } if ( ignoreCount > 0 ) { getLog().info( "Ignored " + ignoreCount + " error" + ( ( ignoreCount > 1 ) ? "s" : "" ) + ", " + count + " violation" + ( ( count > 1 ) ? "s" : "" ) + " remaining." ); } return count; } private void log( String severity, String message ) { if ( "info".equals( severity ) ) { getLog().info( message ); } else if ( "warning".equals( severity ) ) { getLog().warn( message ); } else { getLog().error( message ); } } /** * Checks if the given severity is considered a violation. * * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ private boolean isViolation( String severity ) { if ( "error".equals( severity ) ) { return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "warning".equals( severity ) ) { return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); } else if ( "info".equals( severity ) ) { return "info".equals( violationSeverity ); } else { return false; } } private boolean ignore( List ignores, String source ) { for ( RuleUtil.Matcher ignore : ignores ) { if ( ignore.match( source ) ) { return true; } } return false; } private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; if ( useFile == null ) { stringOutputStream = new ByteArrayOutputStream(); consoleListener = new DefaultLogger( stringOutputStream, false ); } else { OutputStream out = getOutputStream( useFile ); consoleListener = new DefaultLogger( out, true ); } return consoleListener; } private OutputStream getOutputStream( File file ) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); if ( !parentFile.exists() ) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream( file ); } catch ( FileNotFoundException e ) { throw new MojoExecutionException( "Unable to create output stream: " + file, e ); } return fileOutputStream; } private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; if ( StringUtils.isNotEmpty( outputFileFormat ) ) { File resultFile = outputFile; OutputStream out = getOutputStream( resultFile ); if ( "xml".equals( outputFileFormat ) ) { listener = new XMLLogger( out, true ); } else if ( "plain".equals( outputFileFormat ) ) { try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations outputXmlFile = File.createTempFile( "checkstyle-result", ".xml" ); outputXmlFile.deleteOnExit(); OutputStream xmlOut = getOutputStream( outputXmlFile ); CompositeAuditListener compoundListener = new CompositeAuditListener(); compoundListener.addListener( new XMLLogger( xmlOut, true ) ); compoundListener.addListener( new DefaultLogger( out, true ) ); listener = compoundListener; } catch ( IOException e ) { throw new MojoExecutionException( "Unable to create temporary file", e ); } } else { throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'." ); } } return listener; } private List collectArtifacts( String hint ) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); if ( pluginManagement != null ) { artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); } artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); return artifacts; } private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) { List artifacts = new ArrayList<>(); Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); if ( checkstylePlugin != null ) { for ( Dependency dep : checkstylePlugin.getDependencies() ) { // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); artifacts.add( (Artifact) plugin.getArtifactMap().get( depKey ) ); } } return artifacts; } private List getSourceDirectories() { if ( sourceDirectories == null ) { sourceDirectories = project.getCompileSourceRoots(); } List sourceDirs = new ArrayList<>( sourceDirectories.size() ); for ( String sourceDir : sourceDirectories ) { sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); } return sourceDirs; } private List getTestSourceDirectories() { if ( testSourceDirectories == null ) { testSourceDirectories = project.getTestCompileSourceRoots(); } List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); for ( String testSourceDir : testSourceDirectories ) { testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); } return testSourceDirs; } } |
data class | long method, deprecated field, low cohesion, feature envy, long parameter list, data class, large class, message chains, inappropriate intimacy, data clumps, long class | t | t | t | long method, deprecated field, low cohesion, feature envy, long parameter list, large class, message chains, inappropriate intimacy, data clumps, long class | 0 | 11500 | https://github.com/apache/maven-checkstyle-plugin/blob/eee0ba18a70e6d6bd51797c70a83cf844f882286/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java/#L75-L872 | 2 | 1626 | 11500 | minor | |
| 1883 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12289 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 1883 | 12289 | minor | ||
| 1859 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Inconsistent formatting 4. Resource leak - the code is not properly handling and closing resources such as files or connections 5. Potential NullPointerException in line 36 6. Magic numbers - hardcoded values in the code that are not properly explained or documented 7. Possible duplicate code 8. Overcomplicated code - the use of reflection to set caller context could be simplified 9. Lack of exception handling or error checking 10. Possible poor naming of variables and methods | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | Long method2 Feature envy3 Inconsistent formatting 4 Resource leak - the code is not properly handling and closing resources such as files or connections 5 Potential NullPointerException in line 36 6 Magic numbers - hardcoded values in the code that are not properly explained or documented 7 Possible duplicate code 8 Overcomplicated code - the use of reflection to set caller context could be simplified 9 Lack of exception handling or error checking | t | f | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1859 | 12219 | major | ||
| 528 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Commented out code 4. Use of magic numbers 5. Feature envy 6. Use of arrays instead of data structures 7. Poor variable and parameter naming (i.e. angles, it, i) 8. Inconsistent spacing and formatting 9. Lack of proper exception handling 10. Inefficient use of loops and iterators 11. Unnecessary complexity in calculations with geometric parameters | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Long method2 Duplicate code3 Commented out code4 Use of magic numbers5 Feature envy6 Use of arrays instead of data structures7 Poor variable and parameter naming (ie angles, it, i)8 Inconsistent spacing and formatting9 Lack of proper exception handling | t | f | t | it, i)8. Inconsistent spacing and formatting9. Lack of proper exception handling | 0 | 5451 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 528 | 5451 | minor | |
| 1538 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1538 | 11226 | major | |
| 2595 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | long method, data class | t | t | t | long method | 0 | 15005 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 2595 | 15005 | major | |
| 5490 | YES I found bad smells. the bad smells are: 1. Long method, 2. Data class. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method, 2 Data class | t | f | t | 2. Data class. | 0 | 1877 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5490 | 1877 | minor | |
| 544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5546 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 544 | 5546 | minor | ||
| 3663 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnnotationSubstitutionType extends CustomSubstitutionType { private final String name; public AnnotationSubstitutionType(MetaAccessProvider metaAccess, ResolvedJavaType original) { super(original); assert original.getSuperclass().equals(metaAccess.lookupJavaType(Proxy.class)); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(original); ResolvedJavaType annotationInterfaceType = AnnotationSupport.findAnnotationInterfaceType(original); assert annotationInterfaceType.isAssignableFrom(original); assert metaAccess.lookupJavaType(Annotation.class).isAssignableFrom(annotationInterfaceType); String n = annotationInterfaceType.getName(); assert n.endsWith(";"); name = n.substring(0, n.length() - 1) + "$$ProxyImpl;"; } @Override public String getName() { return name; } @Override public String toString() { return "AnnotationType<" + toJavaName(true) + " -> " + original + ">"; } } |
data class | data class | t | t | t | 0 | 8426 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/annotation/AnnotationSubstitutionType.java/#L33-L61 | 1 | 3663 | 8426 | minor | ||
| 1145 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 2 | 1145 | 10111 | minor | ||
| 925 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
data class | data class, long method | t | t | t | long method | 0 | 8311 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 925 | 8311 | major | |
| 454 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ExpressionNode { String evaluateAsString(Context context); Object evaluateAsObject(Context context); long evaluateAsLong(Context context); double evaluateAsDouble(Context context); boolean evaluateAsBoolean(Context context); } |
data class | data class | t | t | t | 0 | 4439 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/template/parser/ExpressionNode.java/#L27-L39 | 1 | 454 | 4439 | critical | ||
| 506 | { "message": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | 1. long method | t | t | f | long method | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 506 | 5141 | minor | |
| 2246 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Large Class, 5. Shotgub surgery, 6. Data class, 7. Commented out code, 8. Manual getter/setter methods, 9. Code duplication. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final class MessageTransfer extends Method { public static final int TYPE = 1025; private int _bodySize; @Override public final int getStructType() { return TYPE; } @Override public final int getSizeWidth() { return 0; } @Override public final int getPackWidth() { return 2; } @Override public final boolean hasPayload() { return true; } @Override public final byte getEncodedTrack() { return Frame.L4; } @Override public final boolean isConnectionControl() { return false; } private short packing_flags = 0; private String destination; private MessageAcceptMode acceptMode; private MessageAcquireMode acquireMode; private Header header; private QpidByteBuffer _body; public MessageTransfer() {} public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, java.nio.ByteBuffer body, Option ... options) { this(destination, acceptMode, acquireMode, header, QpidByteBuffer.wrap(body), options); } public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) { if(destination != null) { setDestination(destination); } if(acceptMode != null) { setAcceptMode(acceptMode); } if(acquireMode != null) { setAcquireMode(acquireMode); } setHeader(header); setBody(body); for (int i=0; i < _options.length; i++) { switch (_options[i]) { case SYNC: this.setSync(true); break; case BATCH: this.setBatch(true); break; case UNRELIABLE: this.setUnreliable(true); break; case NONE: break; default: throw new IllegalArgumentException("invalid option: " + _options[i]); } } } @Override public void dispatch(C context, MethodDelegate delegate) { delegate.messageTransfer(context, this); } public final boolean hasDestination() { return (packing_flags & 256) != 0; } public final MessageTransfer clearDestination() { packing_flags &= ~256; this.destination = null; setDirty(true); return this; } public final String getDestination() { return destination; } public final MessageTransfer setDestination(String value) { this.destination = value; packing_flags |= 256; setDirty(true); return this; } public final MessageTransfer destination(String value) { return setDestination(value); } public final boolean hasAcceptMode() { return (packing_flags & 512) != 0; } public final MessageTransfer clearAcceptMode() { packing_flags &= ~512; this.acceptMode = null; setDirty(true); return this; } public final MessageAcceptMode getAcceptMode() { return acceptMode; } public final MessageTransfer setAcceptMode(MessageAcceptMode value) { this.acceptMode = value; packing_flags |= 512; setDirty(true); return this; } public final MessageTransfer acceptMode(MessageAcceptMode value) { return setAcceptMode(value); } public final boolean hasAcquireMode() { return (packing_flags & 1024) != 0; } public final MessageTransfer clearAcquireMode() { packing_flags &= ~1024; this.acquireMode = null; setDirty(true); return this; } public final MessageAcquireMode getAcquireMode() { return acquireMode; } public final MessageTransfer setAcquireMode(MessageAcquireMode value) { this.acquireMode = value; packing_flags |= 1024; setDirty(true); return this; } public final MessageTransfer acquireMode(MessageAcquireMode value) { return setAcquireMode(value); } @Override public final Header getHeader() { return this.header; } @Override public final void setHeader(Header header) { this.header = header; } public final MessageTransfer header(Header header) { setHeader(header); return this; } @Override public final QpidByteBuffer getBody() { return _body; } @Override public final void setBody(QpidByteBuffer body) { if (body == null) { _bodySize = 0; if (_body != null) { _body.dispose(); } _body = null; } else { _body = body.duplicate(); _bodySize = _body.remaining(); } } @Override public int getBodySize() { return _bodySize; } @Override public void write(Encoder enc) { enc.writeUint16(packing_flags); if ((packing_flags & 256) != 0) { enc.writeStr8(this.destination); } if ((packing_flags & 512) != 0) { enc.writeUint8(this.acceptMode.getValue()); } if ((packing_flags & 1024) != 0) { enc.writeUint8(this.acquireMode.getValue()); } } @Override public void read(Decoder dec) { packing_flags = (short) dec.readUint16(); if ((packing_flags & 256) != 0) { this.destination = dec.readStr8(); } if ((packing_flags & 512) != 0) { this.acceptMode = MessageAcceptMode.get(dec.readUint8()); } if ((packing_flags & 1024) != 0) { this.acquireMode = MessageAcquireMode.get(dec.readUint8()); } } @Override public Map getFields() { Map result = new LinkedHashMap(); if ((packing_flags & 256) != 0) { result.put("destination", getDestination()); } if ((packing_flags & 512) != 0) { result.put("acceptMode", getAcceptMode()); } if ((packing_flags & 1024) != 0) { result.put("acquireMode", getAcquireMode()); } return result; } public void dispose() { if (_body != null) { _body.dispose(); _body = null; } } } |
data class | Long method, 2 Feature envy, 3 Magic numbers, 4 Large Class, 5 Shotgub surgery, 6 Data class, 7 Commented out code, 8 Manual getter/setter methods, 9 Code duplication | t | f | t | . Long method, 2. Feature envy, 3. Magic numbers, 4. Large Class, 5. Shotgub surgery, 7. Commented out code, 8. Manual getter/setter methods, 9. Code duplication. | 0 | 13649 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java/#L31-L312 | 2 | 2246 | 13649 | major | |
| 2673 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | long method | t | t | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 2673 | 15225 | major | ||
| 2089 | { "response": "YES, I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13117 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 2 | 2089 | 13117 | major | |
| 2102 | { "response": "YES, I found bad smells", "detected_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | data class, long method | t | t | t | long method | 0 | 13161 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 2102 | 13161 | minor | |
| 2301 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 14036 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 1 | 2301 | 14036 | minor | |
| 743 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6978 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 2 | 743 | 6978 | major | ||
| 1006 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9258 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1006 | 9258 | major | |
| 353 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | long method | t | t | t | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 1 | 353 | 3634 | major | ||
| 1790 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | 'Long Method', 'Feature Envy' | t | t | t | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',F,e,a,t,u,r,e," ",E,n,v,y,'} | {',L,o,n,g," ",M,h,o,d,',","," ",',F,a," ",n,v,y,'} | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 1 | 1790 | 11987 | minor |
| 1866 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileSinkOptionsMetadata implements ProfileNamesProvider { private static final String USE_SPEL_PROFILE = "use-expression"; private static final String USE_LITERAL_STRING_PROFILE = "use-string"; private boolean binary = false; private String charset = "UTF-8"; private String dir = "/tmp/xd/output/"; private String name = XD_STREAM_NAME; private String suffix = "out"; private Mode mode = APPEND; private String nameExpression; private String dirExpression; @NotNull public Mode getMode() { return mode; } @ModuleOption("what to do if the file already exists") public void setMode(Mode mode) { this.mode = mode; } /** * Return dot + suffix if suffix is set, or the empty string otherwise. */ public String getExtensionWithDot() { return StringUtils.hasText(suffix) ? "." + suffix.trim() : ""; } @ModuleOption("filename extension to use") public void setSuffix(String suffix) { this.suffix = suffix; } public String getName() { return name; } @ModuleOption("filename pattern to use") public void setName(String name) { this.name = name; } @NotBlank public String getDir() { return dir; } @ModuleOption("the directory in which files will be created") public void setDir(String dir) { this.dir = dir; } public boolean isBinary() { return binary; } @ModuleOption("if false, will append a newline character at the end of each line") public void setBinary(boolean binary) { this.binary = binary; } @ModuleOption("the charset to use when writing a String payload") public void setCharset(String charset) { this.charset = charset; } @NotBlank public String getCharset() { return charset; } public String getNameExpression() { return nameExpression; } @ModuleOption("spring expression used to define filename") public void setNameExpression(String nameExpression) { this.nameExpression = nameExpression; } public String getDirExpression() { return dirExpression; } @ModuleOption("spring expression used to define directory name") public void setDirExpression(String dirExpression) { this.dirExpression = dirExpression; } public static enum Mode { APPEND, REPLACE, FAIL, IGNORE; } @Override public String[] profilesToActivate() { return (nameExpression != null || dirExpression != null) ? new String[] { USE_SPEL_PROFILE } : new String[] { USE_LITERAL_STRING_PROFILE }; } } |
data class | data class, long method | t | t | t | long method | 0 | 12238 | https://github.com/spring-projects/spring-xd/blob/ec106725c51d245109b2e5055d9f65e43228ecc1/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/modules/metadata/FileSinkOptionsMetadata.java/#L37-L148 | 1 | 1866 | 12238 | critical | |
| 562 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean mkdirs( ) { return file.mkdirs( ); } |
feature envy | Feature envy | t | f | t | 0 | 5666 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/core/org.eclipse.birt.core/src/org/eclipse/birt/core/fs/LocalFile.java/#L80-L84 | 2 | 562 | 5666 | major | ||
| 5756 | YES I found bad smells the bad smells are: 1.Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long Method | t | f | t | 0 | 14501 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5756 | 14501 | minor | ||
| 2343 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void writeTransactionResponse(ResponseCode response, String explanation) throws IOException { HttpCommunicationsSession commSession = (HttpCommunicationsSession) peer.getCommunicationsSession(); if(TransferDirection.RECEIVE.equals(direction)){ switch (response) { case CONFIRM_TRANSACTION: logger.debug("{} Confirming transaction. checksum={}", this, explanation); commSession.setChecksum(explanation); break; case TRANSACTION_FINISHED: logger.debug("{} Finishing transaction.", this); break; case CANCEL_TRANSACTION: logger.debug("{} Canceling transaction. explanation={}", this, explanation); TransactionResultEntity resultEntity = apiClient.commitReceivingFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION, null); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } break; } } else { switch (response) { case FINISH_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Finished sending flow files.", this); break; case BAD_CHECKSUM: { TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.BAD_CHECKSUM); ResponseCode badChecksumCancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (badChecksumCancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} BAD_CHECKSUM, The transaction is canceled on server properly.", this); break; default: logger.warn("{} BAD_CHECKSUM, Expected the transaction is canceled on server, but received {}.", this, badChecksumCancelResponse); break; } } break; case CONFIRM_TRANSACTION: // The actual HTTP request will be sent in readTransactionResponse. logger.debug("{} Transaction is confirmed.", this); break; case CANCEL_TRANSACTION: { logger.debug("{} Canceling transaction.", this); TransactionResultEntity resultEntity = apiClient.commitTransferFlowFiles(transactionUrl, ResponseCode.CANCEL_TRANSACTION); ResponseCode cancelResponse = ResponseCode.fromCode(resultEntity.getResponseCode()); switch (cancelResponse) { case CANCEL_TRANSACTION: logger.debug("{} CANCEL_TRANSACTION, The transaction is canceled on server properly.", this); break; default: logger.warn("{} CANCEL_TRANSACTION, Expected the transaction is canceled on server, but received {}.", this, cancelResponse); break; } } break; } } } |
long method | data class, long method | t | t | t | data class | 0 | 14182 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-commons/nifi-site-to-site-client/src/main/java/org/apache/nifi/remote/protocol/http/HttpClientTransaction.java/#L110-L176 | 1 | 2343 | 14182 | major | |
| 2001 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | long method | t | t | t | 0 | 12710 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 2001 | 12710 | major | ||
| 591 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { MessageDispatchNotification info = (MessageDispatchNotification)o; int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalLong1(wireFormat, info.getDeliverySequenceId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); return rc + 0; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5901 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-client/src/main/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationMarshaller.java/#L77-L88 | 2 | 591 | 5901 | minor | ||
| 1699 | {"response": "YES I found bad smells", "detected bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class PolyglotExceptionImpl extends AbstractExceptionImpl implements com.oracle.truffle.polyglot.PolyglotImpl.VMObject { private static final String CAUSE_CAPTION = "Caused by host exception: "; private static final boolean TRACE_STACK_TRACE_WALKING = false; private PolyglotException api; final PolyglotContextImpl context; private final PolyglotEngineImpl engine; final Throwable exception; private final List guestFrames; private StackTraceElement[] javaStackTrace; private List materializedFrames; private final SourceSection sourceLocation; private final boolean internal; private final boolean cancelled; private final boolean exit; private final boolean incompleteSource; private final boolean syntaxError; private final int exitStatus; private final Value guestObject; private final String message; private Object fileSystemContext; // Exception coming from a language PolyglotExceptionImpl(PolyglotLanguageContext languageContext, Throwable original) { this(languageContext.getImpl(), languageContext.getEngine(), languageContext, original); } // Exception coming from an instrument PolyglotExceptionImpl(PolyglotEngineImpl engine, Throwable original) { this(engine.impl, engine, null, original); } private PolyglotExceptionImpl(AbstractPolyglotImpl impl, PolyglotEngineImpl engine, PolyglotLanguageContext languageContext, Throwable original) { super(impl); Objects.requireNonNull(engine); this.engine = engine; this.context = (languageContext != null) ? languageContext.context : null; this.exception = original; this.guestFrames = TruffleStackTrace.getStackTrace(original); if (exception instanceof TruffleException) { TruffleException truffleException = (TruffleException) exception; this.internal = truffleException.isInternalError(); this.cancelled = truffleException.isCancelled(); this.syntaxError = truffleException.isSyntaxError(); this.incompleteSource = truffleException.isIncompleteSource(); this.exit = truffleException.isExit(); this.exitStatus = this.exit ? truffleException.getExitStatus() : 0; com.oracle.truffle.api.source.SourceSection section = truffleException.getSourceLocation(); if (section != null) { Objects.requireNonNull(languageContext, "Source location can not be accepted without language context."); com.oracle.truffle.api.source.Source truffleSource = section.getSource(); String language = truffleSource.getLanguage(); if (language == null) { PolyglotLanguage foundLanguage = languageContext.getEngine().findLanguage(language, truffleSource.getMimeType(), false); if (foundLanguage != null) { language = foundLanguage.getId(); } } Source source = getAPIAccess().newSource(language, truffleSource); this.sourceLocation = getAPIAccess().newSourceSection(source, section); } else { this.sourceLocation = null; } Object exceptionObject; if (languageContext != null && !(exception instanceof HostException) && (exceptionObject = ((TruffleException) exception).getExceptionObject()) != null) { /* * Allow proxies in guest language objects. This is for legacy support. Ideally we * should get rid of this if it is no longer relied upon. */ Object receiver = exceptionObject; if (receiver instanceof Proxy) { receiver = languageContext.toGuestValue(receiver); } this.guestObject = languageContext.asValue(receiver); } else { this.guestObject = null; } } else { this.cancelled = false; this.internal = true; this.syntaxError = false; this.incompleteSource = false; this.exit = false; this.exitStatus = 0; this.sourceLocation = null; this.guestObject = null; } if (isHostException()) { this.message = asHostException().getMessage(); } else { if (internal) { this.message = exception.toString(); } else { this.message = exception.getMessage(); } } // late materialization of host frames. only needed if polyglot exceptions cross the // host boundary. VMAccessor.LANGUAGE.materializeHostFrames(original); } @Override public boolean equals(Object obj) { if (obj instanceof PolyglotExceptionImpl) { return exception == ((PolyglotExceptionImpl) obj).exception; } return false; } @Override public int hashCode() { return exception.hashCode(); } @Override public org.graalvm.polyglot.SourceSection getSourceLocation() { return sourceLocation; } @Override public void onCreate(PolyglotException instance) { this.api = instance; } @Override public boolean isHostException() { return exception instanceof HostException; } @Override public Throwable asHostException() { if (!(exception instanceof HostException)) { throw new PolyglotUnsupportedException( String.format("Unsupported operation %s.%s. You can ensure that the operation is supported using %s.%s.", PolyglotException.class.getSimpleName(), "asHostException()", PolyglotException.class.getSimpleName(), "isHostException()")); } return ((HostException) exception).getOriginal(); } @Override public void printStackTrace(PrintWriter s) { printStackTrace(new WrappedPrintWriter(s)); } @Override public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. synchronized (s.lock()) { // Print our stack trace if (isInternalError() || getMessage() == null || getMessage().isEmpty()) { s.println(api); } else { s.println(getMessage()); } materialize(); int languageIdLength = 0; // java for (StackFrame traceElement : getPolyglotStackTrace()) { if (!traceElement.isHostFrame()) { languageIdLength = Math.max(languageIdLength, getAPIAccess().getImpl(traceElement).getLanguage().getId().length()); } } for (StackFrame traceElement : getPolyglotStackTrace()) { s.println("\tat " + getAPIAccess().getImpl(traceElement).toStringImpl(languageIdLength)); } // Print cause, if any if (isHostException()) { s.println(CAUSE_CAPTION + asHostException()); } if (isInternalError()) { s.println("Original Internal Error: "); s.printStackTrace(exception); } } } @Override public String getMessage() { return message; } public StackTraceElement[] getJavaStackTrace() { if (javaStackTrace == null) { materialize(); javaStackTrace = new StackTraceElement[materializedFrames.size()]; for (int i = 0; i < javaStackTrace.length; i++) { javaStackTrace[i] = materializedFrames.get(i).toHostFrame(); } } return javaStackTrace; } private void materialize() { if (this.materializedFrames == null) { List frames = new ArrayList<>(); for (StackFrame frame : getPolyglotStackTrace()) { frames.add(frame); } this.materializedFrames = Collections.unmodifiableList(frames); } } @Override public StackTraceElement[] getStackTrace() { return getJavaStackTrace().clone(); } @Override public PolyglotEngineImpl getEngine() { return engine; } @Override public boolean isInternalError() { return internal; } @Override public Iterable getPolyglotStackTrace() { if (materializedFrames != null) { return materializedFrames; } else { return new Iterable() { public Iterator iterator() { return new StackFrameIterator(PolyglotExceptionImpl.this); } }; } } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isExit() { return exit; } @Override public boolean isIncompleteSource() { return incompleteSource; } @Override public int getExitStatus() { return exitStatus; } @Override public boolean isSyntaxError() { return syntaxError; } @Override public Value getGuestObject() { return guestObject; } Object getFileSystemContext() { if (fileSystemContext != null) { return fileSystemContext; } if (context == null) { return null; } return VMAccessor.LANGUAGE.createFileSystemContext(context.config.fileSystem, context.engine.getFileTypeDetectorsSupplier()); } /** * Wrapper class for PrintStream and PrintWriter to enable a single implementation of * printStackTrace. */ private abstract static class PrintStreamOrWriter { /** Returns the object to be locked when using this StreamOrWriter. */ abstract Object lock(); /** Prints the specified string as a line on this StreamOrWriter. */ abstract void println(Object o); abstract void printStackTrace(Throwable t); } private static class WrappedPrintStream extends PrintStreamOrWriter { private final PrintStream printStream; WrappedPrintStream(PrintStream printStream) { this.printStream = printStream; } @Override Object lock() { return printStream; } @Override void println(Object o) { printStream.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printStream); } } private static class WrappedPrintWriter extends PrintStreamOrWriter { private final PrintWriter printWriter; WrappedPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } @Override Object lock() { return printWriter; } @Override void println(Object o) { printWriter.println(o); } @Override void printStackTrace(Throwable t) { t.printStackTrace(printWriter); } } private static class StackFrameIterator implements Iterator { private static final String POLYGLOT_PACKAGE = Engine.class.getName().substring(0, Engine.class.getName().lastIndexOf('.') + 1); private static final String HOST_INTEROP_PACKAGE = "com.oracle.truffle.polyglot."; private static final String[] JAVA_INTEROP_HOST_TO_GUEST = { HOST_INTEROP_PACKAGE + "PolyglotMap", HOST_INTEROP_PACKAGE + "PolyglotList", HOST_INTEROP_PACKAGE + "PolyglotFunction", HOST_INTEROP_PACKAGE + "FunctionProxyHandler", HOST_INTEROP_PACKAGE + "ObjectProxyHandler" }; final PolyglotExceptionImpl impl; final Iterator guestFrames; final StackTraceElement[] hostStack; final ListIterator hostFrames; /* * Initial host frames are skipped if the error is a regular non-internal guest language * error. */ final APIAccess apiAccess; boolean inHostLanguage; boolean firstGuestFrame = true; PolyglotExceptionFrame fetchedNext; StackFrameIterator(PolyglotExceptionImpl impl) { this.impl = impl; this.apiAccess = impl.getAPIAccess(); Throwable cause = impl.exception; while (cause.getCause() != null && cause.getStackTrace().length == 0) { if (cause instanceof HostException) { cause = ((HostException) cause).getOriginal(); } else { cause = cause.getCause(); } } if (VMAccessor.LANGUAGE.isTruffleStackTrace(cause)) { this.hostStack = VMAccessor.LANGUAGE.getInternalStackTraceElements(cause); } else if (cause.getStackTrace() == null || cause.getStackTrace().length == 0) { this.hostStack = impl.exception.getStackTrace(); } else { this.hostStack = cause.getStackTrace(); } this.guestFrames = impl.guestFrames == null ? Collections. emptyList().iterator() : impl.guestFrames.iterator(); this.hostFrames = Arrays.asList(hostStack).listIterator(); // we always start in some host stack frame this.inHostLanguage = impl.isHostException() || impl.isInternalError(); if (TRACE_STACK_TRACE_WALKING) { // To mark the beginning of the stack trace and separate from the previous one PrintStream out = System.out; out.println(); } } public boolean hasNext() { return fetchNext() != null; } public StackFrame next() { PolyglotExceptionFrame next = fetchNext(); if (next == null) { throw new NoSuchElementException(); } fetchedNext = null; return apiAccess.newPolyglotStackTraceElement(impl.api, next); } PolyglotExceptionFrame fetchNext() { if (fetchedNext != null) { return fetchedNext; } while (hostFrames.hasNext()) { StackTraceElement element = hostFrames.next(); traceStackTraceElement(element); // we need to flip inHostLanguage state in opposite order as the stack is top to // bottom. if (inHostLanguage) { int guestToHost = isGuestToHost(element, hostStack, hostFrames.nextIndex()); if (guestToHost >= 0) { assert !isHostToGuest(element); inHostLanguage = false; for (int i = 0; i < guestToHost; i++) { assert isGuestToHostReflectiveCall(element); element = hostFrames.next(); traceStackTraceElement(element); } assert isGuestToHostCallFromHostInterop(element); } } else { if (isHostToGuest(element)) { inHostLanguage = true; // skip extra host-to-guest frames while (hostFrames.hasNext()) { StackTraceElement next = hostFrames.next(); traceStackTraceElement(next); if (isHostToGuest(next)) { element = next; } else { hostFrames.previous(); break; } } } } if (isGuestCall(element)) { inHostLanguage = false; // construct guest frame TruffleStackTraceElement guestFrame = null; if (guestFrames.hasNext()) { guestFrame = guestFrames.next(); } PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } else if (inHostLanguage) { // construct host frame fetchedNext = (PolyglotExceptionFrame.createHost(impl, element)); return fetchedNext; } else { // skip stack frame that is part of guest language stack } } // consume guest frames if (guestFrames.hasNext()) { TruffleStackTraceElement guestFrame = guestFrames.next(); PolyglotExceptionFrame frame = PolyglotExceptionFrame.createGuest(impl, guestFrame, firstGuestFrame); firstGuestFrame = false; if (frame != null) { fetchedNext = frame; return fetchedNext; } } return null; } static boolean isLazyStackTraceElement(StackTraceElement element) { return element == null; } static boolean isGuestCall(StackTraceElement element) { return isLazyStackTraceElement(element) || VMAccessor.SPI.isGuestCallStackElement(element); } static boolean isHostToGuest(StackTraceElement element) { if (isLazyStackTraceElement(element)) { return false; } if (element.getClassName().startsWith(POLYGLOT_PACKAGE) && element.getClassName().indexOf('.', POLYGLOT_PACKAGE.length()) < 0) { return true; } else if (element.getClassName().startsWith(HOST_INTEROP_PACKAGE)) { for (String hostToGuestClassName : JAVA_INTEROP_HOST_TO_GUEST) { if (element.getClassName().equals(hostToGuestClassName)) { return true; } } } return false; } // Return the number of frames with reflective calls to skip static int isGuestToHost(StackTraceElement firstElement, StackTraceElement[] hostStack, int nextElementIndex) { if (isLazyStackTraceElement(firstElement)) { return -1; } StackTraceElement element = firstElement; int index = nextElementIndex; while (isGuestToHostReflectiveCall(element) && nextElementIndex < hostStack.length) { element = hostStack[index++]; } if (isGuestToHostCallFromHostInterop(element)) { return index - nextElementIndex; } else { return -1; } } private static boolean isGuestToHostCallFromHostInterop(StackTraceElement element) { switch (element.getClassName()) { case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase": return element.getMethodName().equals("invokeHandle"); case "com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MethodReflectImpl": return element.getMethodName().equals("reflectInvoke"); case "com.oracle.truffle.polyglot.PolyglotProxy$ExecuteNode": case "com.oracle.truffle.polyglot.PolyglotProxy$InstantiateNode": case "com.oracle.truffle.polyglot.PolyglotProxy$AsPointerNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayGetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySetNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArrayRemoveNode": case "com.oracle.truffle.polyglot.PolyglotProxy$ArraySizeNode": case "com.oracle.truffle.polyglot.PolyglotProxy$GetMemberKeysNode": case "com.oracle.truffle.polyglot.PolyglotProxy$PutMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$RemoveMemberNode": case "com.oracle.truffle.polyglot.PolyglotProxy$HasMemberNode": return element.getMethodName().equals("executeImpl"); default: return false; } } private static boolean isGuestToHostReflectiveCall(StackTraceElement element) { switch (element.getClassName()) { case "sun.reflect.NativeMethodAccessorImpl": case "sun.reflect.DelegatingMethodAccessorImpl": case "jdk.internal.reflect.NativeMethodAccessorImpl": case "jdk.internal.reflect.DelegatingMethodAccessorImpl": case "java.lang.reflect.Method": return element.getMethodName().startsWith("invoke"); default: return false; } } private void traceStackTraceElement(StackTraceElement element) { if (TRACE_STACK_TRACE_WALKING) { PrintStream out = System.out; out.printf("host: %5s, guestToHost: %2s, hostToGuest: %5s, guestCall: %5s, -- %s %n", inHostLanguage, isGuestToHost(element, hostStack, hostFrames.nextIndex()), isHostToGuest(element), isGuestCall(element), element); } } } } |
data class | data class | t | t | t | 0 | 11734 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/PolyglotExceptionImpl.java/#L69-L651 | 1 | 1699 | 11734 | minor | ||
| 137 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Data Class", "3. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
data class | 1. blob, 2. data class, 3. long method | t | t | t | 1. blob, 3. long method | 0 | 1730 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 1 | 137 | 1730 | major | |
| 2013 | YES I found bad smells the bad smells are: 1. Long method 2. Repetitive code (similar code blocks for different parameters) 3. Data class (the method is only performing data validation, which could be separated into its own class) 4. Feature envy (the use of a different helper class for extracting data) 5. Long parameter list (the method has a large number of parameters) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | Long method2 Repetitive code (similar code blocks for different parameters)3 Data class (the method is only performing data validation, which could be separated into its own class)4 Feature envy (the use of a different helper class for extracting data)5 Long parameter list (the method has a large number of parameters) | t | f | t | which could be separated into its own class)4. Feature envy (the use of a different helper class for extracting data)5. Long parameter list (the method has a large number of parameters) | 0 | 12755 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2013 | 12755 | critical | |
| 238 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | 1. data class | t | t | t | 0 | 2613 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 238 | 2613 | major | ||
| 2645 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method | t | t | t | 0 | 15150 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2645 | 15150 | major | ||
| 997 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (SUGGEST_PLACE) 3. Repeated code 4. Code duplication (calling mLocator.getLoadStatus().name() twice) 5. Inconsistent formatting (explicitly declaring interface type in generic) 6. Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList);) 7. Nested callbacks/functional complexity 8. Hard-coded values (.name() in if statement) 9. Non-descriptive variable names (suggestionsFuture) 10. Negative conditional statements (!mLocator.getLocatorInfo().isSupportsSuggestions()) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | Long method2 Magic numbers (SUGGEST_PLACE)3 Repeated code4 Code duplication (calling mLocatorgetLoadStatus()name() twice)5 Inconsistent formatting (explicitly declaring interface type in generic)6 Feature envy (calling multiple methods from external class mSuggestionsList = suggestionsFutureget(); showSuggestedPlaceNames(mSuggestionsList);)7 Nested callbacks/functional complexity8 Hard-coded values (name() in if statement)9 Non-descriptive variable names (suggestionsFuture) | t | f | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 2 | 997 | 9139 | minor | ||
| 604 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | data class | t | t | t | 0 | 6027 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 604 | 6027 | major | ||
| 880 | YES I found bad smells the bad smells are: 1. Long method 2. Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath) 3. The use of abbreviations (wd, dt, cv) 4. Single letter variable names (f, b, os) 5. Nested loops and conditionals | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | Long method2 Method parameter with different types and responsibilities (consumerHeaderKey, consumerHeaderValue, bundleClassPath)3 The use of abbreviations (wd, dt, cv)4 Single letter variable names (f, b, os)5 Nested loops and conditionals | t | f | t | consumerHeaderValue, bundleClassPath)3. The use of abbreviations (wd, dt, cv)4. Single letter variable names (f, b, os)5. Nested loops and conditionals | 0 | 8016 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 880 | 8016 | major | |
| 1680 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long Method | t | f | t | 0 | 11666 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 1680 | 11666 | minor | ||
| 2166 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 13348 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2166 | 13348 | critical | ||
| 1548 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11258 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1548 | 11258 | minor | ||
| 1986 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method | t | t | t | 0 | 12657 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1986 | 12657 | minor | ||
| 2471 | { "answer": "YES I found bad smells", "detected_bad_smells": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class | t | t | t | 0 | 14578 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 2471 | 14578 | major | ||
| 1152 | YES I found bad smells: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10133 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 1152 | 10133 | minor | |
| 2520 | { "message": "YES I found bad smells", "bad smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void visit(DirectedGraph dg) { CompoundDirectedGraph graph = (CompoundDirectedGraph) dg; NodeList roots = new NodeList(); // Find all subgraphs and root subgraphs for (int i = 0; i < graph.nodes.size(); i++) { Object node = graph.nodes.get(i); if (node instanceof Subgraph) { Subgraph s = (Subgraph) node; Insets padding = dg.getPadding(s); s.head = new SubgraphBoundary(s, padding, 0); s.tail = new SubgraphBoundary(s, padding, 2); Edge headToTail = new Edge(s.head, s.tail); headToTail.weight = 10; graph.edges.add(headToTail); graph.containment.add(headToTail); graph.subgraphs.add(s); if (s.getParent() == null) roots.add(s); if (s.members.size() == 2) // The 2 being the head and tail only graph.edges.add(new Edge(s.head, s.tail)); } } buildNestingTreeIndices(roots, 0); convertSubgraphEndpoints(graph); addContainmentEdges(graph); replaceSubgraphsWithBoundaries(graph); } |
long method | 1. long method | t | t | t | 0 | 14709 | https://github.com/eclipse/gef-legacy/blob/14563a9e1f2af636a5364d195cf07dbff6f35fa6/org.eclipse.draw2d/src/org/eclipse/draw2d/graph/ConvertCompoundGraph.java/#L142-L171 | 1 | 2520 | 14709 | minor | ||
| 2254 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2254 | 13687 | major | ||
| 581 | YES I found bad smells The bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method | t | f | t | 0 | 5786 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 581 | 5786 | major | ||
| 2216 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | data class | t | t | t | 0 | 13536 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 1 | 2216 | 13536 | major | ||
| 629 | { "response": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | data class, long method | t | t | t | long method | 0 | 6279 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 629 | 6279 | critical | |
| 2571 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | long method | t | t | t | 0 | 14900 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 1 | 2571 | 14900 | minor | ||
| 723 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Conditional complexity, 5. Excessive logging, 6. Unnecessary comments | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Conditional complexity, 5 Excessive logging, 6 Unnecessary comments | t | f | t | . Long method, 3. Duplicate code, 4. Conditional complexity, 5. Excessive logging, 6. Unnecessary comments | 0 | 6834 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 723 | 6834 | major | |
| 171 | {"output": "YES I found bad smells\nthe bad smells are: 1. Blob, 2. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = RevokeCertificateCmd.APINAME, description = "Revokes certificate using configured CA plugin", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false, since = "4.11.0", authorized = {RoleType.Admin}) public class RevokeCertificateCmd extends BaseAsyncCmd { public static final String APINAME = "revokeCertificate"; @Inject private CAManager caManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.SERIAL, type = BaseCmd.CommandType.STRING, required = true, description = "The certificate serial number, as a hex value") private String serial; @Parameter(name = ApiConstants.CN, type = BaseCmd.CommandType.STRING, description = "The certificate CN") private String cn; @Parameter(name = ApiConstants.PROVIDER, type = BaseCmd.CommandType.STRING, description = "Name of the CA service provider, otherwise the default configured provider plugin will be used") private String provider; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public BigInteger getSerialBigInteger() { if (Strings.isNullOrEmpty(serial)) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Certificate serial cannot be empty"); } return new BigInteger(serial, 16); } public String getCn() { return cn; } public String getProvider() { return provider; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { boolean result = caManager.revokeCertificate(getSerialBigInteger(), getCn(), getProvider()); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); } @Override public String getCommandName() { return APINAME.toLowerCase() + BaseCmd.RESPONSE_SUFFIX; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } @Override public String getEventType() { return EventTypes.EVENT_CA_CERTIFICATE_REVOKE; } @Override public String getEventDescription() { return "revoking certificate with serial id=" + serial + ", cn=" + cn; } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 2036 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/RevokeCertificateCmd.java/#L39-L116 | 1 | 171 | 2036 | minor | |
| 270 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method | t | t | t | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 1 | 270 | 2901 | minor | ||
| 2562 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class ValidEmail { @Email String newEmail; public String getNewEmail() { return newEmail; } public void setNewEmail(String email) { this.newEmail = email; } } |
data class | data class, long method | t | t | t | long method | 0 | 14843 | https://github.com/cloudfoundry/uaa/blob/f3b66dd2a250c1309a86cade560ac9a9cfeafec7/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java/#L147-L158 | 1 | 2562 | 14843 | major | |
| 4008 | YES I found bad smells The bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
feature envy | Long method2Feature envy | t | f | t | 0 | 10594 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 4008 | 10594 | major | ||
| 1513 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11161 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 1513 | 11161 | major | ||
| 2294 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TagTag extends DefineTagSupport { private String name; public TagTag() { } // Tag interface //------------------------------------------------------------------------- public void doTag(XMLOutput output) throws JellyTagException { getTagLibrary().registerDynamicTag( getName(), getBody() ); } // Properties //------------------------------------------------------------------------- /** @return the name of the tag to create */ public String getName() { return name; } /** Sets the name of the tag to create */ public void setName(String name) { this.name = name; } } |
data class | blob, data class | t | t | t | blob | 0 | 13978 | https://github.com/apache/commons-jelly/blob/48c008cc2328402e0976295625b32c5197ba2324/jelly-tags/define/src/main/java/org/apache/commons/jelly/tags/define/TagTag.java/#L32-L57 | 1 | 2294 | 13978 | minor | |
| 1257 | YES I found bad smells the bad smells are: 1. Long class, 2. Data class, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | Long class, 2 Data class, 3 Feature envy | t | f | t | . Long class, 3. Feature envy | 0 | 10498 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 2 | 1257 | 10498 | major | |
| 2201 | { "answer": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected int height; protected int width; public ImageSource( int width, int height ) { this.width = width; this.height = height; } public int getHeight( ) { return height; } public int getWidth( ) { return width; } public abstract int getRGB( int x, int y ); } public class ArrayImageSource extends ImageSource |
data class | the bad smells are: data class | t | t | t | 0 | 13502 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine.emitter.postscript/src/org/eclipse/birt/report/engine/emitter/postscript/PostscriptWriter.java/#L1340-L1363 | 1 | 2201 | 13502 | major | ||
| 326 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BuildProperties extends AbstractProperties { public BuildProperties(PropertiesAccessor accessor) { super(accessor); } public Map getAllProps() { return accessor.getBuildProperties(); } } |
data class | 1. data class | t | t | t | 0 | 3376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/BuildProperties.java/#L24-L34 | 1 | 326 | 3376 | minor | ||
| 4232 | YES, I found bad smells the bad smells are: 1. Long methods 2. Feature envy 3. Poor exception handling 4. Overuse of if/else statements 5. Mixing of responsibilities (e.g. handling both proxy and transaction logic in one method) 6. Poor variable naming (e.g. "target", "isNewEm") | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
long method | Long methods2 Feature envy3 Poor exception handling 4 Overuse of if/else statements 5 Mixing of responsibilities (eg handling both proxy and transaction logic in one method) 6 Poor variable naming (eg "target", "isNewEm") | t | f | t | "isNewEm") | 0 | 11137 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 4232 | 11137 | critical | |
| 987 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | data class | t | t | t | 0 | 8965 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 987 | 8965 | critical | ||
| 521 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator> iterator() { return immutableComparatorRegistry.iterator(); } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 5410 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/registries/ImmutableComparatorRegistry.java/#L148-L152 | 2 | 521 | 5410 | major | |
| 2110 | YES I found bad smellsthe bad smells are: 1. Long method 2. Repeated code (sentryClient.grantRoleToGroups() and sentryClient.revokeRoleFromGroups()) 3. Mixing of concerns (roles and groups being handled in the same method) 4. Lack of proper error handling (catch block does not handle all types of exceptions) 5. Inconsistent naming conventions (camel case and underscore usage) 6. Using generic exception types instead of specific ones 7. Lack of comments/documentation to explain the purpose of the code and its functionality. 8. Nested try-catch blocks 9. Tight coupling (dependency on specific implementation of SentryClient) 10. Code duplication (grant/revoke functionality is repeated for each role) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Repeated code (sentryClientgrantRoleToGroups() and sentryClientrevokeRoleFromGroups())3 Mixing of concerns (roles and groups being handled in the same method)4 Lack of proper error handling (catch block does not handle all types of exceptions)5 Inconsistent naming conventions (camel case and underscore usage)6 Using generic exception types instead of specific ones7 Lack of comments/documentation to explain the purpose of the code and its functionality8 Nested try-catch blocks9 Tight coupling (dependency on specific implementation of SentryClient) | t | f | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 2110 | 13182 | minor | ||
| 2477 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name="xa_access_audit") public class AuthzAuditEventDbObj implements Serializable { private static final Log LOG = LogFactory.getLog(AuthzAuditEventDbObj.class); private static final long serialVersionUID = 1L; static int MaxValueLengthAccessType = 255; static int MaxValueLengthAclEnforcer = 255; static int MaxValueLengthAgentId = 255; static int MaxValueLengthClientIp = 255; static int MaxValueLengthClientType = 255; static int MaxValueLengthRepoName = 255; static int MaxValueLengthResultReason = 255; static int MaxValueLengthSessionId = 255; static int MaxValueLengthRequestUser = 255; static int MaxValueLengthAction = 2000; static int MaxValueLengthRequestData = 4000; static int MaxValueLengthResourcePath = 4000; static int MaxValueLengthResourceType = 255; private long auditId; private int repositoryType; private String repositoryName; private String user; private Date timeStamp; private String accessType; private String resourcePath; private String resourceType; private String action; private int accessResult; private String agentId; private long policyId; private String resultReason; private String aclEnforcer; private String sessionId; private String clientType; private String clientIP; private String requestData; private long seqNum; private long eventCount; private long eventDurationMS; private String tags; public static void init(Properties props) { LOG.info("AuthzAuditEventDbObj.init()"); final String AUDIT_DB_MAX_COLUMN_VALUE = "xasecure.audit.destination.db.max.column.length"; MaxValueLengthAccessType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "access_type", MaxValueLengthAccessType); logMaxColumnValue("access_type", MaxValueLengthAccessType); MaxValueLengthAclEnforcer = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "acl_enforcer", MaxValueLengthAclEnforcer); logMaxColumnValue("acl_enforcer", MaxValueLengthAclEnforcer); MaxValueLengthAction = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "action", MaxValueLengthAction); logMaxColumnValue("action", MaxValueLengthAction); MaxValueLengthAgentId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "agent_id", MaxValueLengthAgentId); logMaxColumnValue("agent_id", MaxValueLengthAgentId); MaxValueLengthClientIp = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_id", MaxValueLengthClientIp); logMaxColumnValue("client_id", MaxValueLengthClientIp); MaxValueLengthClientType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "client_type", MaxValueLengthClientType); logMaxColumnValue("client_type", MaxValueLengthClientType); MaxValueLengthRepoName = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "repo_name", MaxValueLengthRepoName); logMaxColumnValue("repo_name", MaxValueLengthRepoName); MaxValueLengthResultReason = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "result_reason", MaxValueLengthResultReason); logMaxColumnValue("result_reason", MaxValueLengthResultReason); MaxValueLengthSessionId = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "session_id", MaxValueLengthSessionId); logMaxColumnValue("session_id", MaxValueLengthSessionId); MaxValueLengthRequestUser = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_user", MaxValueLengthRequestUser); logMaxColumnValue("request_user", MaxValueLengthRequestUser); MaxValueLengthRequestData = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "request_data", MaxValueLengthRequestData); logMaxColumnValue("request_data", MaxValueLengthRequestData); MaxValueLengthResourcePath = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_path", MaxValueLengthResourcePath); logMaxColumnValue("resource_path", MaxValueLengthResourcePath); MaxValueLengthResourceType = MiscUtil.getIntProperty(props, AUDIT_DB_MAX_COLUMN_VALUE + "." + "resource_type", MaxValueLengthResourceType); logMaxColumnValue("resource_type", MaxValueLengthResourceType); } public static void logMaxColumnValue(String columnName, int configuredMaxValueLength) { LOG.info("Setting max column value for column[" + columnName + "] to [" + configuredMaxValueLength + "]."); if (configuredMaxValueLength == 0) { LOG.info("Max length of column[" + columnName + "] was 0! Column will NOT be emitted in the audit."); } else if (configuredMaxValueLength < 0) { LOG.info("Max length of column[" + columnName + "] was less than 0! Column value will never be truncated."); } } public AuthzAuditEventDbObj() { super(); } public AuthzAuditEventDbObj(AuthzAuditEvent event) { super(); Date utcDate=null; if(event.getEventTime()!=null){ utcDate=MiscUtil.getUTCDateForLocalDate(event.getEventTime()); }else{ utcDate=MiscUtil.getUTCDate(); } this.repositoryType = event.getRepositoryType(); this.repositoryName = event.getRepositoryName(); this.user = event.getUser(); this.timeStamp = utcDate; this.accessType = event.getAccessType(); this.resourcePath = event.getResourcePath(); this.resourceType = event.getResourceType(); this.action = event.getAction(); this.accessResult = event.getAccessResult(); this.agentId = event.getAgentId(); this.policyId = event.getPolicyId(); this.resultReason = event.getResultReason(); this.aclEnforcer = event.getAclEnforcer(); this.sessionId = event.getSessionId(); this.clientType = event.getClientType(); this.clientIP = event.getClientIP(); this.requestData = event.getRequestData(); this.seqNum = event.getSeqNum(); this.eventCount = event.getEventCount(); this.eventDurationMS= event.getEventDurationMS(); this.tags = StringUtils.join(event.getTags(), ", "); } @Id @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ") @Column(name = "id", unique = true, nullable = false) public long getAuditId() { return this.auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } @Column(name = "repo_type") public int getRepositoryType() { return this.repositoryType; } public void setRepositoryType(int repositoryType) { this.repositoryType = repositoryType; } @Column(name = "repo_name") public String getRepositoryName() { return truncate(this.repositoryName, MaxValueLengthRepoName, "repo_name"); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @Column(name = "request_user") public String getUser() { return truncate(this.user, MaxValueLengthRequestUser, "request_user"); } public void setUser(String user) { this.user = user; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "event_time") public Date getTimeStamp() { return this.timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Column(name = "access_type") public String getAccessType() { return truncate(this.accessType, MaxValueLengthAccessType, "access_type"); } public void setAccessType(String accessType) { this.accessType = accessType; } @Column(name = "resource_path") public String getResourcePath() { return truncate(this.resourcePath, MaxValueLengthResourcePath, "resource_path"); } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } @Column(name = "resource_type") public String getResourceType() { return truncate(this.resourceType, MaxValueLengthResourceType, "resource_type"); } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name = "action") public String getAction() { return truncate(this.action, MaxValueLengthAction, "action"); } public void setAction(String action) { this.action = action; } @Column(name = "access_result") public int getAccessResult() { return this.accessResult; } public void setAccessResult(int accessResult) { this.accessResult = accessResult; } @Column(name = "agent_id") public String getAgentId() { return truncate(this.agentId, MaxValueLengthAgentId, "agent_id"); } public void setAgentId(String agentId) { this.agentId = agentId; } @Column(name = "policy_id") public long getPolicyId() { return this.policyId; } public void setPolicyId(long policyId) { this.policyId = policyId; } @Column(name = "result_reason") public String getResultReason() { return truncate(this.resultReason, MaxValueLengthResultReason, "result_reason"); } public void setResultReason(String resultReason) { this.resultReason = resultReason; } @Column(name = "acl_enforcer") public String getAclEnforcer() { return truncate(this.aclEnforcer, MaxValueLengthAclEnforcer, "acl_enforcer"); } public void setAclEnforcer(String aclEnforcer) { this.aclEnforcer = aclEnforcer; } @Column(name = "session_id") public String getSessionId() { return truncate(this.sessionId, MaxValueLengthSessionId, "session_id"); } public void setSessionId(String sessionId) { this.sessionId = sessionId; } @Column(name = "client_type") public String getClientType() { return truncate(this.clientType, MaxValueLengthClientType, "client_type"); } public void setClientType(String clientType) { this.clientType = clientType; } @Column(name = "client_ip") public String getClientIP() { return truncate(this.clientIP, MaxValueLengthClientIp, "client_ip"); } public void setClientIP(String clientIP) { this.clientIP = clientIP; } @Column(name = "request_data") public String getRequestData() { return truncate(this.requestData, MaxValueLengthRequestData, "request_data"); } public void setRequestData(String requestData) { this.requestData = requestData; } @Column(name = "seq_num") public long getSeqNum() { return this.seqNum; } public void setSeqNum(long seqNum) { this.seqNum = seqNum; } @Column(name = "event_count") public long getEventCount() { return this.eventCount; } public void setEventCount(long eventCount) { this.eventCount = eventCount; } @Column(name = "event_dur_ms") public long getEventDurationMS() { return this.eventDurationMS; } public void setEventDurationMS(long eventDurationMS) { this.eventDurationMS = eventDurationMS; } @Column(name = "tags") public String getTags() { return this.tags; } public void setTags(String tags) { this.tags = tags; } static final String TruncationMarker = "..."; static final int TruncationMarkerLength = TruncationMarker.length(); protected String truncate(String value, int limit, String columnName) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> getTrunctedValue(%s, %d, %s)", value, limit, columnName)); } String result = value; if (value != null) { if (limit < 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncation is suppressed for column[%s]: old value [%s], new value[%s]", columnName, value, result)); } } else if (limit == 0) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Column[%s] is to be excluded from audit: old value [%s], new value[%s]", columnName, value, result)); } result = null; } else { if (value.length() > limit) { if (limit <= TruncationMarkerLength) { // NOTE: If value is to be truncated to a size that is less than of equal to the Truncation Marker then we won't put the marker in!! result = value.substring(0, limit); } else { StringBuilder sb = new StringBuilder(value.substring(0, limit - TruncationMarkerLength)); sb.append(TruncationMarker); result = sb.toString(); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("Truncating value for column[%s] to [%d] characters: old value [%s], new value[%s]", columnName, limit, value, result)); } } } } if (LOG.isDebugEnabled()) { LOG.debug(String.format("<== getTrunctedValue(%s, %d, %s): %s", value, limit, columnName, result)); } return result; } } |
data class | long method, data class | t | t | t | long method | 0 | 14589 | https://github.com/apache/ranger/blob/7c52a79a5d0b41bfc94caca9d531e0fefba2bfe7/agents-audit/src/main/java/org/apache/ranger/audit/entity/AuthzAuditEventDbObj.java/#L46-L412 | 1 | 2477 | 14589 | critical | |
| 662 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6455 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 662 | 6455 | minor | ||
| 811 | { "response": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | data class, long method | t | t | t | long method | 0 | 7650 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 1 | 811 | 7650 | minor | |
| 2179 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 13412 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 2179 | 13412 | minor | ||
| 624 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static org.apache.phoenix.coprocessor.generated.MetaDataProtos.CreateFunctionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6250 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L8189-L8194 | 2 | 624 | 6250 | minor | ||
| 2084 | {"answer": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 13082 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 1 | 2084 | 13082 | major | |
| 444 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ConfigurationProperties(prefix = "camel.opentracing") public class OpenTracingConfigurationProperties { /** * Sets exclude pattern(s) that will disable tracing for Camel messages that * matches the pattern. */ private Set excludePatterns; /** * Activate or deactivate dash encoding in headers (required by JMS) for * messaging */ private Boolean encoding; public Set getExcludePatterns() { return excludePatterns; } public void setExcludePatterns(Set excludePatterns) { this.excludePatterns = excludePatterns; } public Boolean getEncoding() { return encoding; } public void setEncoding(Boolean encoding) { this.encoding = encoding; } } |
data class | data class | t | t | t | 0 | 4319 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/platforms/spring-boot/components-starter/camel-opentracing-starter/src/main/java/org/apache/camel/opentracing/starter/OpenTracingConfigurationProperties.java/#L23-L52 | 1 | 444 | 4319 | minor | ||
| 2272 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 13768 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2272 | 13768 | major | |
| 2198 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | the bad smells are: long method | t | t | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 2198 | 13492 | major | ||
| 2072 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | long method | t | t | t | 0 | 13027 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 1 | 2072 | 13027 | major | ||
| 4113 | {"answer": "YES I found bad smells", "detected_bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CovarianceMatricesAggregator implements Serializable { /** Serial version uid. */ private static final long serialVersionUID = 4163253784526780812L; /** Mean vector. */ private final Vector mean; /** Weighted by P(c|xi) sum of (xi - mean) * (xi - mean)^T values. */ private Matrix weightedSum; /** Count of rows. */ private int rowCount; /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. */ CovarianceMatricesAggregator(Vector mean) { this.mean = mean; } /** * Creates an instance of CovarianceMatricesAggregator. * * @param mean Mean vector. * @param weightedSum Weighted sums for covariace computation. * @param rowCount Count of rows. */ CovarianceMatricesAggregator(Vector mean, Matrix weightedSum, int rowCount) { this.mean = mean; this.weightedSum = weightedSum; this.rowCount = rowCount; } /** * Computes covatiation matrices for feature vector for each GMM component. * * @param dataset Dataset. * @param clusterProbs Probabilities of each GMM component. * @param means Means for each GMM component. */ static List computeCovariances(Dataset dataset, Vector clusterProbs, Vector[] means) { List aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; } /** * @param x Feature vector (xi). * @param pcxi P(c|xi) for GMM component "c" and vector xi. */ void add(Vector x, double pcxi) { Matrix deltaCol = x.minus(mean).toMatrix(false); Matrix weightedCovComponent = deltaCol.times(deltaCol.transpose()).times(pcxi); if (weightedSum == null) weightedSum = weightedCovComponent; else weightedSum = weightedSum.plus(weightedCovComponent); rowCount += 1; } /** * @param other Other. * @return sum of aggregators. */ CovarianceMatricesAggregator plus(CovarianceMatricesAggregator other) { A.ensure(this.mean.equals(other.mean), "this.mean == other.mean"); return new CovarianceMatricesAggregator( mean, this.weightedSum.plus(other.weightedSum), this.rowCount + other.rowCount ); } /** * Map stage for covariance computation over dataset. * * @param data Data partition. * @param means Means vector. * @return Covariance aggregators. */ static List map(GmmPartitionData data, Vector[] means) { int countOfComponents = means.length; List aggregators = new ArrayList<>(); for (int i = 0; i < countOfComponents; i++) aggregators.add(new CovarianceMatricesAggregator(means[i])); for (int i = 0; i < data.size(); i++) { for (int c = 0; c < countOfComponents; c++) aggregators.get(c).add(data.getX(i), data.pcxi(c, i)); } return aggregators; } /** * @param clusterProb GMM component probability. * @return computed covariance matrix. */ private Matrix covariance(double clusterProb) { return weightedSum.divide(rowCount * clusterProb); } /** * Reduce stage for covariance computation over dataset. * * @param l first partition. * @param r second partition. */ static List reduce(List l, List r) { A.ensure(l != null || r != null, "Both partitions cannot equal to null"); if (l == null || l.isEmpty()) return r; if (r == null || r.isEmpty()) return l; A.ensure(l.size() == r.size(), "l.size() == r.size()"); List res = new ArrayList<>(); for (int i = 0; i < l.size(); i++) res.add(l.get(i).plus(r.get(i))); return res; } /** * @return mean vector. */ Vector mean() { return mean.copy(); } /** * @return weighted sum. */ Matrix weightedSum() { return weightedSum.copy(); } /** * @return rows count. */ public int rowCount() { return rowCount; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10831 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/ml/src/main/java/org/apache/ignite/ml/clustering/gmm/CovarianceMatricesAggregator.java/#L34-L196 | 1 | 4113 | 10831 | minor | |
| 457 | YES I found bad smells the bad smells are: 1.Long method, 2.Data class, 3.Feature envy, 4.Magic number, 5.Duplicate code, 6.Inappropriate constant, 7.Message chains | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | Long method, 2Data class, 3Feature envy, 4Magic number, 5Duplicate code, 6Inappropriate constant, 7Message chains | t | f | t | .Long method, 3.Feature envy, 4.Magic number, 5.Duplicate code, 6.Inappropriate constant, 7.Message chains | 0 | 4454 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 2 | 457 | 4454 | minor | |
| 678 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class PutFileAction implements SshAction { // TODO support backup as a property? private SFTPClient sftp; private final String path; private final int permissionsMask; private final long lastModificationDate; private final long lastAccessDate; private final int uid; private final Supplier contentsSupplier; private final Integer length; PutFileAction(Map props, String path, Supplier contentsSupplier, long length) { String permissions = getOptionalVal(props, PROP_PERMISSIONS); long lastModificationDateVal = getOptionalVal(props, PROP_LAST_MODIFICATION_DATE); long lastAccessDateVal = getOptionalVal(props, PROP_LAST_ACCESS_DATE); if (lastAccessDateVal <= 0 ^ lastModificationDateVal <= 0) { lastAccessDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); lastModificationDateVal = Math.max(lastAccessDateVal, lastModificationDateVal); } this.permissionsMask = Integer.parseInt(permissions, 8); this.lastAccessDate = lastAccessDateVal; this.lastModificationDate = lastModificationDateVal; this.uid = getOptionalVal(props, PROP_OWNER_UID); this.path = checkNotNull(path, "path"); this.contentsSupplier = checkNotNull(contentsSupplier, "contents"); this.length = Ints.checkedCast(checkNotNull((long)length, "size")); } @Override public void clear() { closeWhispering(sftp, this); sftp = null; } @Override public Void create() throws Exception { final AtomicReference inputStreamRef = new AtomicReference(); sftp = acquire(sftpConnection); try { sftp.put(new InMemorySourceFile() { @Override public String getName() { return path; } @Override public long getLength() { return length; } @Override public InputStream getInputStream() throws IOException { InputStream contents = contentsSupplier.get(); inputStreamRef.set(contents); return contents; } }, path); sftp.chmod(path, permissionsMask); if (uid != -1) { sftp.chown(path, uid); } if (lastAccessDate > 0) { sftp.setattr(path, new FileAttributes.Builder() .withAtimeMtime(lastAccessDate, lastModificationDate) .build()); } } finally { closeWhispering(inputStreamRef.get(), this); } return null; } @Override public String toString() { return "Put(path=[" + path + " "+length+"])"; } } |
data class | data class, long method | t | t | t | long method | 0 | 6584 | https://github.com/apache/incubator-brooklyn/blob/337a5d22d5e9c98cc96ea1085383cbed1ee0b741/brooklyn-server/core/src/main/java/org/apache/brooklyn/util/core/internal/ssh/sshj/SshjTool.java/#L730-L802 | 1 | 678 | 6584 | minor | |
| 34 | { "message": "YES, I found bad smells", "bad smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 742 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 34 | 742 | major | |
| 2610 | {"response":"YES I found bad smells","the bad smells are":["Blob","Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MetadataTableUtil { private static final Text EMPTY_TEXT = new Text(); private static final byte[] EMPTY_BYTES = new byte[0]; private static Map root_tables = new HashMap<>(); private static Map metadata_tables = new HashMap<>(); private static final Logger log = LoggerFactory.getLogger(MetadataTableUtil.class); private MetadataTableUtil() {} public static synchronized Writer getMetadataTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer metadataTable = metadata_tables.get(credentials); if (metadataTable == null) { metadataTable = new Writer(context, MetadataTable.ID); metadata_tables.put(credentials, metadataTable); } return metadataTable; } public static synchronized Writer getRootTable(ServerContext context) { Credentials credentials = context.getCredentials(); Writer rootTable = root_tables.get(credentials); if (rootTable == null) { rootTable = new Writer(context, RootTable.ID); root_tables.put(credentials, rootTable); } return rootTable; } public static void putLockID(ServerContext context, ZooLock zooLock, Mutation m) { TabletsSection.ServerColumnFamily.LOCK_COLUMN.put(m, new Value(zooLock.getLockID().serialize(context.getZooKeeperRoot() + "/").getBytes(UTF_8))); } private static void update(ServerContext context, Mutation m, KeyExtent extent) { update(context, null, m, extent); } public static void update(ServerContext context, ZooLock zooLock, Mutation m, KeyExtent extent) { Writer t = extent.isMeta() ? getRootTable(context) : getMetadataTable(context); update(context, t, zooLock, m); } public static void update(ServerContext context, Writer t, ZooLock zooLock, Mutation m) { if (zooLock != null) putLockID(context, zooLock, m); while (true) { try { t.update(m); return; } catch (AccumuloException | TableNotFoundException | AccumuloSecurityException e) { log.error("{}", e.getMessage(), e); } catch (ConstraintViolationException e) { log.error("{}", e.getMessage(), e); // retrying when a CVE occurs is probably futile and can cause problems, see ACCUMULO-3096 throw new RuntimeException(e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } public static void updateTabletFlushID(KeyExtent extent, long flushID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(m, new Value((flushID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletCompactID(KeyExtent extent, long compactID, ServerContext context, ZooLock zooLock) { if (!extent.isRootTablet()) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.COMPACT_COLUMN.put(m, new Value((compactID + "").getBytes(UTF_8))); update(context, zooLock, m, extent); } } public static void updateTabletDataFile(long tid, KeyExtent extent, Map estSizes, String time, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); byte[] tidBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : estSizes.entrySet()) { Text file = entry.getKey().meta(); m.put(DataFileColumnFamily.NAME, file, new Value(entry.getValue().encode())); m.put(TabletsSection.BulkFileColumnFamily.NAME, file, new Value(tidBytes)); } TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value(time.getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void updateTabletDir(KeyExtent extent, String newDir, ServerContext context, ZooLock lock) { Mutation m = new Mutation(extent.getMetadataEntry()); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, lock, m, extent); } public static void addTablet(KeyExtent extent, String path, ServerContext context, char timeType, ZooLock lock) { Mutation m = extent.getPrevRowUpdateMutation(); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(path.getBytes(UTF_8))); TabletsSection.ServerColumnFamily.TIME_COLUMN.put(m, new Value((timeType + "0").getBytes(UTF_8))); update(context, lock, m, extent); } public static void updateTabletVolumes(KeyExtent extent, List logsToRemove, List logsToAdd, List filesToRemove, SortedMap filesToAdd, String newDir, ZooLock zooLock, ServerContext context) { if (extent.isRootTablet()) { if (newDir != null) throw new IllegalArgumentException("newDir not expected for " + extent); if (filesToRemove.size() != 0 || filesToAdd.size() != 0) throw new IllegalArgumentException("files not expected for " + extent); // add before removing in case of process death for (LogEntry logEntry : logsToAdd) addRootLogEntry(context, zooLock, logEntry); removeUnusedWALEntries(context, extent, logsToRemove, zooLock); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry logEntry : logsToRemove) m.putDelete(logEntry.getColumnFamily(), logEntry.getColumnQualifier()); for (LogEntry logEntry : logsToAdd) m.put(logEntry.getColumnFamily(), logEntry.getColumnQualifier(), logEntry.getValue()); for (FileRef fileRef : filesToRemove) m.putDelete(DataFileColumnFamily.NAME, fileRef.meta()); for (Entry entry : filesToAdd.entrySet()) m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); if (newDir != null) ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(newDir.getBytes(UTF_8))); update(context, m, extent); } } private interface ZooOperation { void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException; } private static void retryZooKeeperUpdate(ServerContext context, ZooLock zooLock, ZooOperation op) { while (true) { try { IZooReaderWriter zoo = context.getZooReaderWriter(); if (zoo.isLockHeld(zooLock.getLockID())) { op.run(zoo); } break; } catch (Exception e) { log.error("Unexpected exception {}", e.getMessage(), e); } sleepUninterruptibly(1, TimeUnit.SECONDS); } } private static void addRootLogEntry(ServerContext context, ZooLock zooLock, final LogEntry entry) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException, IOException { String root = getZookeeperLogLocation(context); rw.putPersistentData(root + "/" + entry.getUniqueID(), entry.toBytes(), NodeExistsPolicy.OVERWRITE); } }); } public static SortedMap getDataFileSizes(KeyExtent extent, ServerContext context) { TreeMap sizes = new TreeMap<>(); try (Scanner mdScanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { mdScanner.fetchColumnFamily(DataFileColumnFamily.NAME); Text row = extent.getMetadataEntry(); Key endKey = new Key(row, DataFileColumnFamily.NAME, new Text("")); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); mdScanner.setRange(new Range(new Key(row), endKey)); for (Entry entry : mdScanner) { if (!entry.getKey().getRow().equals(row)) break; DataFileValue dfv = new DataFileValue(entry.getValue().get()); sizes.put(new FileRef(context.getVolumeManager(), entry.getKey()), dfv); } return sizes; } } public static void rollBackSplit(Text metadataEntry, Text oldPrevEndRow, ServerContext context, ZooLock zooLock) { KeyExtent ke = new KeyExtent(metadataEntry, oldPrevEndRow); Mutation m = ke.getPrevRowUpdateMutation(); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void splitTablet(KeyExtent extent, Text oldPrevEndRow, double splitRatio, ServerContext context, ZooLock zooLock) { Mutation m = extent.getPrevRowUpdateMutation(); // TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.put(m, new Value(Double.toString(splitRatio).getBytes(UTF_8))); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.put(m, KeyExtent.encodePrevEndRow(oldPrevEndRow)); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); update(context, zooLock, m, extent); } public static void finishSplit(Text metadataEntry, Map datafileSizes, List highDatafilesToRemove, final ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(metadataEntry); TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN.putDelete(m); TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.putDelete(m); ChoppedColumnFamily.CHOPPED_COLUMN.putDelete(m); for (Entry entry : datafileSizes.entrySet()) { m.put(DataFileColumnFamily.NAME, entry.getKey().meta(), new Value(entry.getValue().encode())); } for (FileRef pathToRemove : highDatafilesToRemove) { m.putDelete(DataFileColumnFamily.NAME, pathToRemove.meta()); } update(context, zooLock, m, new KeyExtent(metadataEntry, (Text) null)); } public static void finishSplit(KeyExtent extent, Map datafileSizes, List highDatafilesToRemove, ServerContext context, ZooLock zooLock) { finishSplit(extent.getMetadataEntry(), datafileSizes, highDatafilesToRemove, context, zooLock); } public static void addDeleteEntries(KeyExtent extent, Set datafilesToDelete, ServerContext context) { TableId tableId = extent.getTableId(); // TODO could use batch writer,would need to handle failure and retry like update does - // ACCUMULO-1294 for (FileRef pathToRemove : datafilesToDelete) { update(context, createDeleteMutation(context, tableId, pathToRemove.path().toString()), extent); } } public static void addDeleteEntry(ServerContext context, TableId tableId, String path) { update(context, createDeleteMutation(context, tableId, path), new KeyExtent(tableId, null, null)); } public static Mutation createDeleteMutation(ServerContext context, TableId tableId, String pathToRemove) { Path path = context.getVolumeManager().getFullPath(tableId, pathToRemove); Mutation delFlag = new Mutation(new Text(MetadataSchema.DeletesSection.getRowPrefix() + path)); delFlag.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); return delFlag; } public static void removeScanFiles(KeyExtent extent, Set scanFiles, ServerContext context, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); for (FileRef pathToRemove : scanFiles) m.putDelete(ScanFileColumnFamily.NAME, pathToRemove.meta()); update(context, zooLock, m, extent); } public static void splitDatafiles(Text midRow, double splitRatio, Map firstAndLastRows, SortedMap datafiles, SortedMap lowDatafileSizes, SortedMap highDatafileSizes, List highDatafilesToRemove) { for (Entry entry : datafiles.entrySet()) { Text firstRow = null; Text lastRow = null; boolean rowsKnown = false; FileUtil.FileInfo mfi = firstAndLastRows.get(entry.getKey()); if (mfi != null) { firstRow = mfi.getFirstRow(); lastRow = mfi.getLastRow(); rowsKnown = true; } if (rowsKnown && firstRow.compareTo(midRow) > 0) { // only in high long highSize = entry.getValue().getSize(); long highEntries = entry.getValue().getNumEntries(); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } else if (rowsKnown && lastRow.compareTo(midRow) <= 0) { // only in low long lowSize = entry.getValue().getSize(); long lowEntries = entry.getValue().getNumEntries(); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); highDatafilesToRemove.add(entry.getKey()); } else { long lowSize = (long) Math.floor((entry.getValue().getSize() * splitRatio)); long lowEntries = (long) Math.floor((entry.getValue().getNumEntries() * splitRatio)); lowDatafileSizes.put(entry.getKey(), new DataFileValue(lowSize, lowEntries, entry.getValue().getTime())); long highSize = (long) Math.ceil((entry.getValue().getSize() * (1.0 - splitRatio))); long highEntries = (long) Math .ceil((entry.getValue().getNumEntries() * (1.0 - splitRatio))); highDatafileSizes.put(entry.getKey(), new DataFileValue(highSize, highEntries, entry.getValue().getTime())); } } } public static void deleteTable(TableId tableId, boolean insertDeletes, ServerContext context, ZooLock lock) throws AccumuloException { try (Scanner ms = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY); BatchWriter bw = new BatchWriterImpl(context, MetadataTable.ID, new BatchWriterConfig().setMaxMemory(1000000) .setMaxLatency(120000L, TimeUnit.MILLISECONDS).setMaxWriteThreads(2))) { // scan metadata for our table and delete everything we find Mutation m = null; ms.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); // insert deletes before deleting data from metadata... this makes the code fault tolerant if (insertDeletes) { ms.fetchColumnFamily(DataFileColumnFamily.NAME); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.fetch(ms); for (Entry cell : ms) { Key key = cell.getKey(); if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) { FileRef ref = new FileRef(context.getVolumeManager(), key); bw.addMutation(createDeleteMutation(context, tableId, ref.meta().toString())); } if (TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.hasColumns(key)) { bw.addMutation(createDeleteMutation(context, tableId, cell.getValue().toString())); } } bw.flush(); ms.clearColumns(); } for (Entry cell : ms) { Key key = cell.getKey(); if (m == null) { m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } if (key.getRow().compareTo(m.getRow(), 0, m.getRow().length) != 0) { bw.addMutation(m); m = new Mutation(key.getRow()); if (lock != null) putLockID(context, lock, m); } m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); } if (m != null) bw.addMutation(m); } } static String getZookeeperLogLocation(ServerContext context) { return context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_WALOGS; } public static void setRootTabletDir(ServerContext context, String dir) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { zoo.putPersistentData(zpath, dir.getBytes(UTF_8), -1, NodeExistsPolicy.OVERWRITE); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static String getRootTabletDir(ServerContext context) throws IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String zpath = context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_PATH; try { return new String(zoo.getData(zpath, null), UTF_8); } catch (KeeperException e) { throw new IOException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } public static Pair,SortedMap> getFileAndLogEntries( ServerContext context, KeyExtent extent) throws KeeperException, InterruptedException, IOException { ArrayList result = new ArrayList<>(); TreeMap sizes = new TreeMap<>(); VolumeManager fs = context.getVolumeManager(); if (extent.isRootTablet()) { getRootLogEntries(context, result); Path rootDir = new Path(getRootTabletDir(context)); FileStatus[] files = fs.listStatus(rootDir); for (FileStatus fileStatus : files) { if (fileStatus.getPath().toString().endsWith("_tmp")) { continue; } DataFileValue dfv = new DataFileValue(0, 0); sizes.put(new FileRef(fileStatus.getPath().toString(), fileStatus.getPath()), dfv); } } else { try (TabletsMetadata tablets = TabletsMetadata.builder().forTablet(extent).fetchFiles() .fetchLogs().fetchPrev().build(context)) { TabletMetadata tablet = Iterables.getOnlyElement(tablets); if (!tablet.getExtent().equals(extent)) throw new RuntimeException( "Unexpected extent " + tablet.getExtent() + " expected " + extent); result.addAll(tablet.getLogs()); tablet.getFilesMap().forEach((k, v) -> { sizes.put(new FileRef(k, fs.getFullPath(tablet.getTableId(), k)), v); }); } } return new Pair<>(result, sizes); } public static List getLogEntries(ServerContext context, KeyExtent extent) throws IOException, KeeperException, InterruptedException { log.info("Scanning logging entries for {}", extent); ArrayList result = new ArrayList<>(); if (extent.equals(RootTable.EXTENT)) { log.info("Getting logs for root tablet from zookeeper"); getRootLogEntries(context, result); } else { log.info("Scanning metadata for logs used for tablet {}", extent); Scanner scanner = getTabletLogScanner(context, extent); Text pattern = extent.getMetadataEntry(); for (Entry entry : scanner) { Text row = entry.getKey().getRow(); if (entry.getKey().getColumnFamily().equals(LogColumnFamily.NAME)) { if (row.equals(pattern)) { result.add(LogEntry.fromKeyValue(entry.getKey(), entry.getValue())); } } } } log.info("Returning logs {} for extent {}", result, extent); return result; } static void getRootLogEntries(ServerContext context, final ArrayList result) throws KeeperException, InterruptedException, IOException { IZooReaderWriter zoo = context.getZooReaderWriter(); String root = getZookeeperLogLocation(context); // there's a little race between getting the children and fetching // the data. The log can be removed in between. while (true) { result.clear(); for (String child : zoo.getChildren(root)) { try { LogEntry e = LogEntry.fromBytes(zoo.getData(root + "/" + child, null)); // upgrade from !0;!0<< -> +r<< e = new LogEntry(RootTable.EXTENT, 0, e.server, e.filename); result.add(e); } catch (KeeperException.NoNodeException ex) { continue; } } break; } } private static Scanner getTabletLogScanner(ServerContext context, KeyExtent extent) { TableId tableId = MetadataTable.ID; if (extent.isMeta()) tableId = RootTable.ID; Scanner scanner = new ScannerImpl(context, tableId, Authorizations.EMPTY); scanner.fetchColumnFamily(LogColumnFamily.NAME); Text start = extent.getMetadataEntry(); Key endKey = new Key(start, LogColumnFamily.NAME); endKey = endKey.followingKey(PartialKey.ROW_COLFAM); scanner.setRange(new Range(new Key(start), endKey)); return scanner; } private static class LogEntryIterator implements Iterator { Iterator zookeeperEntries = null; Iterator rootTableEntries = null; Iterator> metadataEntries = null; LogEntryIterator(ServerContext context) throws IOException, KeeperException, InterruptedException { zookeeperEntries = getLogEntries(context, RootTable.EXTENT).iterator(); rootTableEntries = getLogEntries(context, new KeyExtent(MetadataTable.ID, null, null)) .iterator(); try { Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); log.info("Setting range to {}", MetadataSchema.TabletsSection.getRange()); scanner.setRange(MetadataSchema.TabletsSection.getRange()); scanner.fetchColumnFamily(LogColumnFamily.NAME); metadataEntries = scanner.iterator(); } catch (Exception ex) { throw new IOException(ex); } } @Override public boolean hasNext() { return zookeeperEntries.hasNext() || rootTableEntries.hasNext() || metadataEntries.hasNext(); } @Override public LogEntry next() { if (zookeeperEntries.hasNext()) { return zookeeperEntries.next(); } if (rootTableEntries.hasNext()) { return rootTableEntries.next(); } Entry entry = metadataEntries.next(); return LogEntry.fromKeyValue(entry.getKey(), entry.getValue()); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static Iterator getLogEntries(ServerContext context) throws IOException, KeeperException, InterruptedException { return new LogEntryIterator(context); } public static void removeUnusedWALEntries(ServerContext context, KeyExtent extent, final List entries, ZooLock zooLock) { if (extent.isRootTablet()) { retryZooKeeperUpdate(context, zooLock, new ZooOperation() { @Override public void run(IZooReaderWriter rw) throws KeeperException, InterruptedException { String root = getZookeeperLogLocation(context); for (LogEntry entry : entries) { String path = root + "/" + entry.getUniqueID(); log.debug("Removing " + path + " from zookeeper"); rw.recursiveDelete(path, NodeMissingPolicy.SKIP); } } }); } else { Mutation m = new Mutation(extent.getMetadataEntry()); for (LogEntry entry : entries) { m.putDelete(entry.getColumnFamily(), entry.getColumnQualifier()); } update(context, zooLock, m, extent); } } private static void getFiles(Set files, Collection tabletFiles, TableId srcTableId) { for (String file : tabletFiles) { if (srcTableId != null && !file.startsWith("../") && !file.contains(":")) { file = "../" + srcTableId + file; } files.add(file); } } private static Mutation createCloneMutation(TableId srcTableId, TableId tableId, Map tablet) { KeyExtent ke = new KeyExtent(tablet.keySet().iterator().next().getRow(), (Text) null); Mutation m = new Mutation(TabletsSection.getRow(tableId, ke.getEndRow())); for (Entry entry : tablet.entrySet()) { if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) { String cf = entry.getKey().getColumnQualifier().toString(); if (!cf.startsWith("../") && !cf.contains(":")) cf = "../" + srcTableId + entry.getKey().getColumnQualifier(); m.put(entry.getKey().getColumnFamily(), new Text(cf), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.CurrentLocationColumnFamily.NAME)) { m.put(TabletsSection.LastLocationColumnFamily.NAME, entry.getKey().getColumnQualifier(), entry.getValue()); } else if (entry.getKey().getColumnFamily() .equals(TabletsSection.LastLocationColumnFamily.NAME)) { // skip } else { m.put(entry.getKey().getColumnFamily(), entry.getKey().getColumnQualifier(), entry.getValue()); } } return m; } private static Iterable createCloneScanner(String testTableName, TableId tableId, AccumuloClient client) throws TableNotFoundException { String tableName; Range range; if (testTableName != null) { tableName = testTableName; range = TabletsSection.getRange(tableId); } else if (tableId.equals(MetadataTable.ID)) { tableName = RootTable.NAME; range = TabletsSection.getRange(); } else { tableName = MetadataTable.NAME; range = TabletsSection.getRange(tableId); } return TabletsMetadata.builder().scanTable(tableName).overRange(range).checkConsistency() .saveKeyValues().fetchFiles().fetchLocation().fetchLast().fetchCloned().fetchPrev() .fetchTime().build(client); } @VisibleForTesting public static void initializeClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator ti = createCloneScanner(testTableName, srcTableId, client).iterator(); if (!ti.hasNext()) throw new RuntimeException(" table deleted during clone? srcTableId = " + srcTableId); while (ti.hasNext()) bw.addMutation(createCloneMutation(srcTableId, tableId, ti.next().getKeyValues())); bw.flush(); } private static int compareEndRows(Text endRow1, Text endRow2) { return new KeyExtent(TableId.of("0"), endRow1, null) .compareTo(new KeyExtent(TableId.of("0"), endRow2, null)); } @VisibleForTesting public static int checkClone(String testTableName, TableId srcTableId, TableId tableId, AccumuloClient client, BatchWriter bw) throws TableNotFoundException, MutationsRejectedException { Iterator srcIter = createCloneScanner(testTableName, srcTableId, client) .iterator(); Iterator cloneIter = createCloneScanner(testTableName, tableId, client) .iterator(); if (!cloneIter.hasNext() || !srcIter.hasNext()) throw new RuntimeException( " table deleted during clone? srcTableId = " + srcTableId + " tableId=" + tableId); int rewrites = 0; while (cloneIter.hasNext()) { TabletMetadata cloneTablet = cloneIter.next(); Text cloneEndRow = cloneTablet.getEndRow(); HashSet cloneFiles = new HashSet<>(); boolean cloneSuccessful = cloneTablet.getCloned() != null; if (!cloneSuccessful) getFiles(cloneFiles, cloneTablet.getFiles(), null); List srcTablets = new ArrayList<>(); TabletMetadata srcTablet = srcIter.next(); srcTablets.add(srcTablet); Text srcEndRow = srcTablet.getEndRow(); int cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); HashSet srcFiles = new HashSet<>(); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); while (cmp > 0) { srcTablet = srcIter.next(); srcTablets.add(srcTablet); srcEndRow = srcTablet.getEndRow(); cmp = compareEndRows(cloneEndRow, srcEndRow); if (cmp < 0) throw new TabletDeletedException( "Tablets deleted from src during clone : " + cloneEndRow + " " + srcEndRow); if (!cloneSuccessful) getFiles(srcFiles, srcTablet.getFiles(), srcTableId); } if (cloneSuccessful) continue; if (!srcFiles.containsAll(cloneFiles)) { // delete existing cloned tablet entry Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); for (Entry entry : cloneTablet.getKeyValues().entrySet()) { Key k = entry.getKey(); m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), k.getTimestamp()); } bw.addMutation(m); for (TabletMetadata st : srcTablets) bw.addMutation(createCloneMutation(srcTableId, tableId, st.getKeyValues())); rewrites++; } else { // write out marker that this tablet was successfully cloned Mutation m = new Mutation(cloneTablet.getExtent().getMetadataEntry()); m.put(ClonedColumnFamily.NAME, new Text(""), new Value("OK".getBytes(UTF_8))); bw.addMutation(m); } } bw.flush(); return rewrites; } public static void cloneTable(ServerContext context, TableId srcTableId, TableId tableId, VolumeManager volumeManager) throws Exception { try (BatchWriter bw = context.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { while (true) { try { initializeClone(null, srcTableId, tableId, context, bw); // the following loop looks changes in the file that occurred during the copy.. if files // were dereferenced then they could have been GCed while (true) { int rewrites = checkClone(null, srcTableId, tableId, context, bw); if (rewrites == 0) break; } bw.flush(); break; } catch (TabletDeletedException tde) { // tablets were merged in the src table bw.flush(); // delete what we have cloned and try again deleteTable(tableId, false, context, null); log.debug("Tablets merged in table {} while attempting to clone, trying again", srcTableId); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } } // delete the clone markers and create directory entries Scanner mscanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY); mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(ClonedColumnFamily.NAME); int dirCount = 0; for (Entry entry : mscanner) { Key k = entry.getKey(); Mutation m = new Mutation(k.getRow()); m.putDelete(k.getColumnFamily(), k.getColumnQualifier()); VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(tableId, new KeyExtent(k.getRow(), (Text) null).getEndRow(), context); String dir = volumeManager.choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + new String( FastFormat.toZeroPaddedString(dirCount++, 8, 16, Constants.CLONE_PREFIX_BYTES)); TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(m, new Value(dir.getBytes(UTF_8))); bw.addMutation(m); } } } public static void chopped(ServerContext context, KeyExtent extent, ZooLock zooLock) { Mutation m = new Mutation(extent.getMetadataEntry()); ChoppedColumnFamily.CHOPPED_COLUMN.put(m, new Value("chopped".getBytes(UTF_8))); update(context, zooLock, m, extent); } public static void removeBulkLoadEntries(AccumuloClient client, TableId tableId, long tid) throws Exception { try ( Scanner mscanner = new IsolatedScanner( client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)); BatchWriter bw = client.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig())) { mscanner.setRange(new KeyExtent(tableId, null, null).toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); byte[] tidAsBytes = Long.toString(tid).getBytes(UTF_8); for (Entry entry : mscanner) { log.trace("Looking at entry {} with tid {}", entry, tid); if (Arrays.equals(entry.getValue().get(), tidAsBytes)) { log.trace("deleting entry {}", entry); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.putDelete(key.getColumnFamily(), key.getColumnQualifier()); bw.addMutation(m); } } } } public static List getBulkFilesLoaded(ServerContext context, AccumuloClient client, KeyExtent extent, long tid) { List result = new ArrayList<>(); try (Scanner mscanner = new IsolatedScanner(client.createScanner( extent.isMeta() ? RootTable.NAME : MetadataTable.NAME, Authorizations.EMPTY))) { VolumeManager fs = context.getVolumeManager(); mscanner.setRange(extent.toMetadataRange()); mscanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : mscanner) { if (Long.parseLong(entry.getValue().toString()) == tid) { result.add(new FileRef(fs, entry.getKey())); } } return result; } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException("Onos! teh metadata table has vanished!!"); } } public static Map> getBulkFilesLoaded(ServerContext context, KeyExtent extent) { Text metadataRow = extent.getMetadataEntry(); Map> result = new HashMap<>(); VolumeManager fs = context.getVolumeManager(); try (Scanner scanner = new ScannerImpl(context, extent.isMeta() ? RootTable.ID : MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(new Range(metadataRow)); scanner.fetchColumnFamily(TabletsSection.BulkFileColumnFamily.NAME); for (Entry entry : scanner) { Long tid = Long.parseLong(entry.getValue().toString()); List lst = result.get(tid); if (lst == null) { result.put(tid, lst = new ArrayList<>()); } lst.add(new FileRef(fs, entry.getKey())); } } return result; } public static void addBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.put(EMPTY_TEXT, EMPTY_TEXT, new Value(new byte[] {})); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } public static void removeBulkLoadInProgressFlag(ServerContext context, String path) { Mutation m = new Mutation(MetadataSchema.BlipSection.getRowPrefix() + path); m.putDelete(EMPTY_TEXT, EMPTY_TEXT); // new KeyExtent is only added to force update to write to the metadata table, not the root // table // because bulk loads aren't supported to the metadata table update(context, m, new KeyExtent(TableId.of("anythingNotMetadata"), null, null)); } /** * During an upgrade from 1.6 to 1.7, we need to add the replication table */ public static void createReplicationTable(ServerContext context) { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironmentImpl(ReplicationTable.ID, null, context); String dir = context.getVolumeManager().choose(chooserEnv, ServerConstants.getBaseUris(context)) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + ReplicationTable.ID + Constants.DEFAULT_TABLET_LOCATION; Mutation m = new Mutation(new Text(TabletsSection.getRow(ReplicationTable.ID, null))); m.put(DIRECTORY_COLUMN.getColumnFamily(), DIRECTORY_COLUMN.getColumnQualifier(), 0, new Value(dir.getBytes(UTF_8))); m.put(TIME_COLUMN.getColumnFamily(), TIME_COLUMN.getColumnQualifier(), 0, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(UTF_8))); m.put(PREV_ROW_COLUMN.getColumnFamily(), PREV_ROW_COLUMN.getColumnQualifier(), 0, KeyExtent.encodePrevEndRow(null)); update(context, getMetadataTable(context), null, m); } /** * During an upgrade we need to move deletion requests for files under the !METADATA table to the * root tablet. */ public static void moveMetaDeleteMarkers(ServerContext context) { String oldDeletesPrefix = "!!~del"; Range oldDeletesRange = new Range(oldDeletesPrefix, true, "!!~dem", false); // move old delete markers to new location, to standardize table schema between all metadata // tables try (Scanner scanner = new ScannerImpl(context, RootTable.ID, Authorizations.EMPTY)) { scanner.setRange(oldDeletesRange); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(oldDeletesPrefix)) { moveDeleteEntry(context, RootTable.OLD_EXTENT, entry, row, oldDeletesPrefix); } else { break; } } } } public static void moveMetaDeleteMarkersFrom14(ServerContext context) { // new KeyExtent is only added to force update to write to the metadata table, not the root // table KeyExtent notMetadata = new KeyExtent(TableId.of("anythingNotMetadata"), null, null); // move delete markers from the normal delete keyspace to the root tablet delete keyspace if the // files are for the !METADATA table try (Scanner scanner = new ScannerImpl(context, MetadataTable.ID, Authorizations.EMPTY)) { scanner.setRange(MetadataSchema.DeletesSection.getRange()); for (Entry entry : scanner) { String row = entry.getKey().getRow().toString(); if (row.startsWith(MetadataSchema.DeletesSection.getRowPrefix() + "/" + MetadataTable.ID)) { moveDeleteEntry(context, notMetadata, entry, row, MetadataSchema.DeletesSection.getRowPrefix()); } else { break; } } } } private static void moveDeleteEntry(ServerContext context, KeyExtent oldExtent, Entry entry, String rowID, String prefix) { String filename = rowID.substring(prefix.length()); // add the new entry first log.info("Moving {} marker in {}", filename, RootTable.NAME); Mutation m = new Mutation(MetadataSchema.DeletesSection.getRowPrefix() + filename); m.put(EMPTY_BYTES, EMPTY_BYTES, EMPTY_BYTES); update(context, m, RootTable.EXTENT); // then remove the old entry m = new Mutation(entry.getKey().getRow()); m.putDelete(EMPTY_BYTES, EMPTY_BYTES); update(context, m, oldExtent); } public static SortedMap> getTabletEntries( SortedMap tabletKeyValues, List columns) { TreeMap> tabletEntries = new TreeMap<>(); HashSet colSet = null; if (columns != null) { colSet = new HashSet<>(columns); } for (Entry entry : tabletKeyValues.entrySet()) { ColumnFQ currentKey = new ColumnFQ(entry.getKey()); if (columns != null && !colSet.contains(currentKey)) { continue; } Text row = entry.getKey().getRow(); SortedMap colVals = tabletEntries.get(row); if (colVals == null) { colVals = new TreeMap<>(); tabletEntries.put(row, colVals); } colVals.put(currentKey, entry.getValue()); } return tabletEntries; } } |
blob | blob, long method, data class | t | t | t | long method, data class | 0 | 15035 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/server/base/src/main/java/org/apache/accumulo/server/util/MetadataTableUtil.java/#L106-L1133 | 1 | 2610 | 15035 | minor | |
| 1010 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method | t | t | t | 0 | 9270 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 1010 | 9270 | minor | ||
| 1503 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on EntityManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManager proxy. return hashCode(); } else if (method.getName().equals("toString")) { // Deliver toString without touching a target EntityManager. return "Shared EntityManager proxy for target factory [" + this.targetFactory + "]"; } else if (method.getName().equals("getEntityManagerFactory")) { // JPA 2.0: return EntityManagerFactory without creating an EntityManager. return this.targetFactory; } else if (method.getName().equals("getCriteriaBuilder") || method.getName().equals("getMetamodel")) { // JPA 2.0: return EntityManagerFactory's CriteriaBuilder/Metamodel (avoid creation of EntityManager) try { return EntityManagerFactory.class.getMethod(method.getName()).invoke(this.targetFactory); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } else if (method.getName().equals("unwrap")) { // JPA 2.0: handle unwrap method - could be a proxy match. Class targetClass = (Class) args[0]; if (targetClass != null && targetClass.isInstance(proxy)) { return proxy; } } else if (method.getName().equals("isOpen")) { // Handle isOpen method: always return true. return true; } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. return null; } else if (method.getName().equals("getTransaction")) { throw new IllegalStateException( "Not allowed to create transaction on shared EntityManager - " + "use Spring transactions or EJB CMT instead"); } // Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; } else if (method.getName().equals("unwrap")) { Class targetClass = (Class) args[0]; if (targetClass == null) { return (target != null ? target : proxy); } // We need a transactional target now. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } // Still perform unwrap call on target EntityManager. } else if (transactionRequiringMethods.contains(method.getName())) { // We need a transactional target now, according to the JPA spec. // Otherwise, the operation would get accepted but remain unflushed... if (target == null || (!TransactionSynchronizationManager.isActualTransactionActive() && !target.getTransaction().isActive())) { throw new TransactionRequiredException("No EntityManager with actual transaction available " + "for current thread - cannot reliably process '" + method.getName() + "' call"); } } // Regular EntityManager operations. boolean isNewEm = false; if (target == null) { logger.debug("Creating new EntityManager for shared EntityManager invocation"); target = (!CollectionUtils.isEmpty(this.properties) ? this.targetFactory.createEntityManager(this.properties) : this.targetFactory.createEntityManager()); isNewEm = true; } // Invoke method on current EntityManager. try { Object result = method.invoke(target, args); if (result instanceof Query) { Query query = (Query) result; if (isNewEm) { Class[] ifcs = ClassUtils.getAllInterfacesForClass(query.getClass(), this.proxyClassLoader); result = Proxy.newProxyInstance(this.proxyClassLoader, ifcs, new DeferredQueryInvocationHandler(query, target)); isNewEm = false; } else { EntityManagerFactoryUtils.applyTransactionTimeout(query, this.targetFactory); } } return result; } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { if (isNewEm) { EntityManagerFactoryUtils.closeEntityManager(target); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11136 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java/#L212-L331 | 2 | 1503 | 11136 | minor | ||
| 1580 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method, data class | t | t | t | data class | 0 | 11359 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1580 | 11359 | critical | |
| 2106 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if(mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if(mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if(!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } } |
blob | blob, long method | t | t | t | long method | 0 | 13171 | https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/.mvn/wrapper/MavenWrapperDownloader.java/#L25-L110 | 1 | 2106 | 13171 | minor | |
| 1042 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | long method | t | t | t | 0 | 9438 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 1 | 1042 | 9438 | major | ||
| 4573 | { "message": "YES, I found bad smells", "bad_smells": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | feature envy, long method | t | t | t | feature envy | 0 | 12153 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/opc-ua-sdk/sdk-server/src/main/java/org/eclipse/milo/opcua/sdk/server/namespaces/loader/UaVariableLoader.java/#L1265-L1278 | 1 | 4573 | 12153 | minor | |
| 3334 | YES I found bad smells,the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6247 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 3334 | 6247 | critical | ||
| 2660 | { "answer": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SlaveSynchronize { private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private final BrokerController brokerController; private volatile String masterAddr = null; public SlaveSynchronize(BrokerController brokerController) { this.brokerController = brokerController; } public String getMasterAddr() { return masterAddr; } public void setMasterAddr(String masterAddr) { this.masterAddr = masterAddr; } public void syncAll() { this.syncTopicConfig(); this.syncConsumerOffset(); this.syncDelayOffset(); this.syncSubscriptionGroupConfig(); } private void syncTopicConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { TopicConfigSerializeWrapper topicWrapper = this.brokerController.getBrokerOuterAPI().getAllTopicConfig(masterAddrBak); if (!this.brokerController.getTopicConfigManager().getDataVersion() .equals(topicWrapper.getDataVersion())) { this.brokerController.getTopicConfigManager().getDataVersion() .assignNewOne(topicWrapper.getDataVersion()); this.brokerController.getTopicConfigManager().getTopicConfigTable().clear(); this.brokerController.getTopicConfigManager().getTopicConfigTable() .putAll(topicWrapper.getTopicConfigTable()); this.brokerController.getTopicConfigManager().persist(); log.info("Update slave topic config from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncTopicConfig Exception, {}", masterAddrBak, e); } } } private void syncConsumerOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { ConsumerOffsetSerializeWrapper offsetWrapper = this.brokerController.getBrokerOuterAPI().getAllConsumerOffset(masterAddrBak); this.brokerController.getConsumerOffsetManager().getOffsetTable() .putAll(offsetWrapper.getOffsetTable()); this.brokerController.getConsumerOffsetManager().persist(); log.info("Update slave consumer offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncConsumerOffset Exception, {}", masterAddrBak, e); } } } private void syncDelayOffset() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { String delayOffset = this.brokerController.getBrokerOuterAPI().getAllDelayOffset(masterAddrBak); if (delayOffset != null) { String fileName = StorePathConfigHelper.getDelayOffsetStorePath(this.brokerController .getMessageStoreConfig().getStorePathRootDir()); try { MixAll.string2File(delayOffset, fileName); } catch (IOException e) { log.error("Persist file Exception, {}", fileName, e); } } log.info("Update slave delay offset from master, {}", masterAddrBak); } catch (Exception e) { log.error("SyncDelayOffset Exception, {}", masterAddrBak, e); } } } private void syncSubscriptionGroupConfig() { String masterAddrBak = this.masterAddr; if (masterAddrBak != null && !masterAddrBak.equals(brokerController.getBrokerAddr())) { try { SubscriptionGroupWrapper subscriptionWrapper = this.brokerController.getBrokerOuterAPI() .getAllSubscriptionGroupConfig(masterAddrBak); if (!this.brokerController.getSubscriptionGroupManager().getDataVersion() .equals(subscriptionWrapper.getDataVersion())) { SubscriptionGroupManager subscriptionGroupManager = this.brokerController.getSubscriptionGroupManager(); subscriptionGroupManager.getDataVersion().assignNewOne( subscriptionWrapper.getDataVersion()); subscriptionGroupManager.getSubscriptionGroupTable().clear(); subscriptionGroupManager.getSubscriptionGroupTable().putAll( subscriptionWrapper.getSubscriptionGroupTable()); subscriptionGroupManager.persist(); log.info("Update slave Subscription Group from master, {}", masterAddrBak); } } catch (Exception e) { log.error("SyncSubscriptionGroup Exception, {}", masterAddrBak, e); } } } } |
data class | data class, long method | t | t | t | long method | 0 | 15192 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/slave/SlaveSynchronize.java/#L31-L144 | 1 | 2660 | 15192 | minor | |
| 1050 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 9476 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1050 | 9476 | major | ||
| 2015 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
long method | 1: long method | t | t | f | long method | 0 | 12768 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 1 | 2015 | 12768 | minor | |
| 2133 | {"message": "YES I found bad smells the bad smells are:", "bad_smells": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 13238 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 1 | 2133 | 13238 | major | |
| 1201 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProcessorUtils { public static final String AVAILABLE_PROCESSORS = "JETTY_AVAILABLE_PROCESSORS"; private static int __availableProcessors = init(); static int init() { String processors = System.getProperty(AVAILABLE_PROCESSORS, System.getenv(AVAILABLE_PROCESSORS)); if (processors != null) { try { return Integer.parseInt( processors ); } catch (NumberFormatException ignored) { } } return Runtime.getRuntime().availableProcessors(); } /** * Returns the number of available processors, from System Property "JETTY_AVAILABLE_PROCESSORS", * or if not set then from environment variable "JETTY_AVAILABLE_PROCESSORS" or if not set then * from {@link Runtime#availableProcessors()}. * * @return the number of processors */ public static int availableProcessors() { return __availableProcessors; } public static void setAvailableProcessors(int processors) { if (processors < 1) throw new IllegalArgumentException("Invalid number of processors: " + processors); __availableProcessors = processors; } } |
data class | long method, data class | t | t | t | long method | 0 | 10284 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-util/src/main/java/org/eclipse/jetty/util/ProcessorUtils.java/#L27-L66 | 1 | 1201 | 10284 | critical | |
| 2499 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | long method, data class | t | t | t | data class | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 2499 | 14652 | critical | |
| 1880 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12284 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 1880 | 12284 | major | |
| 782 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 782 | 7477 | minor | ||
| 372 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Value { int count = 0; BigInteger txid; } |
data class | 1. data class | t | t | f | data class | 0 | 3859 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/com/alipay/dw/jstorm/transcation/TransactionalGlobalCount.java/#L93-L96 | 1 | 372 | 3859 | major | |
| 701 | in the Airavata Registry * * * * @param authenticationToken The token which is generated by Airavata API server * * @param gatewayId The gateway for which the new experiment should be associated with * * @param experiment Experiment Model * * @return The server-side generated experiment-model identifier * * @throws RegistryServiceException * */YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Useless comments, 5 Code duplication, 6 Exception swallowing | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Useless comments, 5. Code duplication, 6. Exception swallowing | 0 | 6688 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 701 | 6688 | major | |
| 4093 | {"message": "YES I found bad smells", "the bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | data class | t | t | f | 0 | 10786 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 4093 | 10786 | major | ||
| 506 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 5141 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 2 | 506 | 5141 | minor | ||
| 2286 | YES I found bad smells The bad smells are: 1. Long parameter list, 2. Long method, 3. Feature envy (getFullContentOctets), 4. Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5. Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 6. Data class (only contains data and no behavior), 7. Inconsistent importing (some classes are imported with the full package name, others are not), 8. Lack of documentation or comments, 9. Duplication of code (the second constructor calls the first one), 10. Primitive obsession (use of primitive data types rather than creating custom objects), 11. Unnecessary constructor (the second constructor is not needed since it just calls the first one with an additional parameter), 12. Lack of cohesion (the class handles both message properties and attachments), 13. Unnecessary public access modifiers (the methods could be made private since they are only used within the class), 14. Lack of abstraction (the class directly accesses the SharedInputStream rather than using a more abstract layer). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
data class | Long parameter list, 2 Long method, 3 Feature envy (getFullContentOctets), 4 Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5 Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 6 Data class (only contains data and no behavior), 7 Inconsistent importing (some classes are imported with the full package name, others are not), 8 Lack of documentation or comments, 9 Duplication of code (the second constructor calls the first one), | t | f | t | . Long parameter list, 2. Long method, 3. Feature envy (getFullContentOctets), 4. Inappropriate intimacy (The class has access to the internals of SharedInputStream rather than using encapsulation), 5. Inconsistent naming conventions (size and textualLineCount variables start with lowercase but subType and mediaType start with uppercase), 7. Inconsistent importing (some classes are imported with the full package name, others are not), 8. Lack of documentation or comments, 9. Duplication of code (the second constructor calls the first one), | 0 | 13880 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 2 | 2286 | 13880 | major | |
| 2 | {"message":"YES I found bad smells","the bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UnorderedPartitionedKVWriter extends BaseUnorderedPartitionedKVWriter { private static final Logger LOG = LoggerFactory.getLogger(UnorderedPartitionedKVWriter.class); private static final int INT_SIZE = 4; private static final int NUM_META = 3; // Number of meta fields. private static final int INDEX_KEYLEN = 0; // KeyLength index private static final int INDEX_VALLEN = 1; // ValLength index private static final int INDEX_NEXT = 2; // Next Record Index. private static final int META_SIZE = NUM_META * INT_SIZE; // Size of total meta-data private final static int APPROX_HEADER_LENGTH = 150; // Maybe setup a separate statistics class which can be shared between the // buffer and the main path instead of having multiple arrays. private final String destNameTrimmed; private final long availableMemory; @VisibleForTesting final WrappedBuffer[] buffers; @VisibleForTesting final BlockingQueue availableBuffers; private final ByteArrayOutputStream baos; private final NonSyncDataOutputStream dos; @VisibleForTesting WrappedBuffer currentBuffer; private final FileSystem rfs; @VisibleForTesting final List spillInfoList = Collections.synchronizedList(new ArrayList()); private final ListeningExecutorService spillExecutor; private final int[] numRecordsPerPartition; private long localOutputRecordBytesCounter; private long localOutputBytesWithOverheadCounter; private long localOutputRecordsCounter; // notify after x records private static final int NOTIFY_THRESHOLD = 1000; // uncompressed size for each partition private final long[] sizePerPartition; private volatile long spilledSize = 0; static final ThreadLocal deflater = new ThreadLocal() { @Override public Deflater initialValue() { return TezCommonUtils.newBestCompressionDeflater(); } @Override public Deflater get() { Deflater deflater = super.get(); deflater.reset(); return deflater; } }; private final Semaphore availableSlots; /** * Represents final number of records written (spills are not counted) */ protected final TezCounter outputLargeRecordsCounter; @VisibleForTesting int numBuffers; @VisibleForTesting int sizePerBuffer; @VisibleForTesting int lastBufferSize; @VisibleForTesting int numInitializedBuffers; @VisibleForTesting int spillLimit; private Throwable spillException; private AtomicBoolean isShutdown = new AtomicBoolean(false); @VisibleForTesting final AtomicInteger numSpills = new AtomicInteger(0); private final AtomicInteger pendingSpillCount = new AtomicInteger(0); @VisibleForTesting Path finalIndexPath; @VisibleForTesting Path finalOutPath; //for single partition cases (e.g UnorderedKVOutput) private final IFile.Writer writer; @VisibleForTesting final boolean skipBuffers; private final ReentrantLock spillLock = new ReentrantLock(); private final Condition spillInProgress = spillLock.newCondition(); private final boolean pipelinedShuffle; private final boolean isFinalMergeEnabled; // To store events when final merge is disabled private final List finalEvents; // How partition stats should be reported. final ReportPartitionStats reportPartitionStats; private final long indexFileSizeEstimate; private List filledBuffers = new ArrayList<>(); public UnorderedPartitionedKVWriter(OutputContext outputContext, Configuration conf, int numOutputs, long availableMemoryBytes) throws IOException { super(outputContext, conf, numOutputs); Preconditions.checkArgument(availableMemoryBytes >= 0, "availableMemory should be >= 0 bytes"); this.destNameTrimmed = TezUtilsInternal.cleanVertexName(outputContext.getDestinationVertexName()); //Not checking for TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT as it might not add much value in // this case. Add it later if needed. boolean pipelinedShuffleConf = this.conf.getBoolean(TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED, TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED_DEFAULT); this.isFinalMergeEnabled = conf.getBoolean( TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT, TezRuntimeConfiguration.TEZ_RUNTIME_ENABLE_FINAL_MERGE_IN_OUTPUT_DEFAULT); this.pipelinedShuffle = pipelinedShuffleConf && !isFinalMergeEnabled; this.finalEvents = Lists.newLinkedList(); if (availableMemoryBytes == 0) { Preconditions.checkArgument(((numPartitions == 1) && !pipelinedShuffle), "availableMemory " + "can be set to 0 only when numPartitions=1 and " + TezRuntimeConfiguration .TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + " is disabled. current numPartitions=" + numPartitions + ", " + TezRuntimeConfiguration.TEZ_RUNTIME_PIPELINED_SHUFFLE_ENABLED + "=" + pipelinedShuffle); } // Ideally, should be significantly larger. availableMemory = availableMemoryBytes; // Allow unit tests to control the buffer sizes. int maxSingleBufferSizeBytes = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_MAX_PER_BUFFER_SIZE_BYTES, Integer.MAX_VALUE); computeNumBuffersAndSize(maxSingleBufferSizeBytes); availableBuffers = new LinkedBlockingQueue(); buffers = new WrappedBuffer[numBuffers]; // Set up only the first buffer to start with. buffers[0] = new WrappedBuffer(numOutputs, sizePerBuffer); numInitializedBuffers = 1; if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Initializing Buffer #" + numInitializedBuffers + " with size=" + sizePerBuffer); } currentBuffer = buffers[0]; baos = new ByteArrayOutputStream(); dos = new NonSyncDataOutputStream(baos); keySerializer.open(dos); valSerializer.open(dos); rfs = ((LocalFileSystem) FileSystem.getLocal(this.conf)).getRaw(); int maxThreads = Math.max(2, numBuffers/2); //TODO: Make use of TezSharedExecutor later ExecutorService executor = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat( "UnorderedOutSpiller {" + TezUtilsInternal.cleanVertexName( outputContext.getDestinationVertexName()) + "} #%d") .build() ); // to restrict submission of more tasks than threads (e.g numBuffers > numThreads) // This is maxThreads - 1, to avoid race between callback thread releasing semaphore and the // thread calling tryAcquire. availableSlots = new Semaphore(maxThreads - 1, true); spillExecutor = MoreExecutors.listeningDecorator(executor); numRecordsPerPartition = new int[numPartitions]; reportPartitionStats = ReportPartitionStats.fromString( conf.get(TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS, TezRuntimeConfiguration.TEZ_RUNTIME_REPORT_PARTITION_STATS_DEFAULT)); sizePerPartition = (reportPartitionStats.isEnabled()) ? new long[numPartitions] : null; outputLargeRecordsCounter = outputContext.getCounters().findCounter( TaskCounter.OUTPUT_LARGE_RECORDS); indexFileSizeEstimate = numPartitions * Constants.MAP_OUTPUT_INDEX_RECORD_LENGTH; if (numPartitions == 1 && !pipelinedShuffle) { //special case, where in only one partition is available. finalOutPath = outputFileHandler.getOutputFileForWrite(); finalIndexPath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); skipBuffers = true; writer = new IFile.Writer(conf, rfs, finalOutPath, keyClass, valClass, codec, outputRecordsCounter, outputRecordBytesCounter); } else { skipBuffers = false; writer = null; } LOG.info(destNameTrimmed + ": " + "numBuffers=" + numBuffers + ", sizePerBuffer=" + sizePerBuffer + ", skipBuffers=" + skipBuffers + ", numPartitions=" + numPartitions + ", availableMemory=" + availableMemory + ", maxSingleBufferSizeBytes=" + maxSingleBufferSizeBytes + ", pipelinedShuffle=" + pipelinedShuffle + ", isFinalMergeEnabled=" + isFinalMergeEnabled + ", numPartitions=" + numPartitions + ", reportPartitionStats=" + reportPartitionStats); } private static final int ALLOC_OVERHEAD = 64; private void computeNumBuffersAndSize(int bufferLimit) { numBuffers = (int)(availableMemory / bufferLimit); if (numBuffers >= 2) { sizePerBuffer = bufferLimit - ALLOC_OVERHEAD; lastBufferSize = (int)(availableMemory % bufferLimit); // Use leftover memory last buffer only if the leftover memory > 50% of bufferLimit if (lastBufferSize > bufferLimit / 2) { numBuffers += 1; } else { if (lastBufferSize > 0) { LOG.warn("Underallocating memory. Unused memory size: {}.", lastBufferSize); } lastBufferSize = sizePerBuffer; } } else { // We should have minimum of 2 buffers. numBuffers = 2; if (availableMemory / numBuffers > Integer.MAX_VALUE) { sizePerBuffer = Integer.MAX_VALUE; } else { sizePerBuffer = (int)(availableMemory / numBuffers); } // 2 equal sized buffers. lastBufferSize = sizePerBuffer; } // Ensure allocation size is multiple of INT_SIZE, truncate down. sizePerBuffer = sizePerBuffer - (sizePerBuffer % INT_SIZE); lastBufferSize = lastBufferSize - (lastBufferSize % INT_SIZE); int mergePercent = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_PARTITIONED_KVWRITER_BUFFER_MERGE_PERCENT_DEFAULT); spillLimit = numBuffers * mergePercent / 100; // Keep within limits. if (spillLimit < 1) { spillLimit = 1; } if (spillLimit > numBuffers) { spillLimit = numBuffers; } } @Override public void write(Object key, Object value) throws IOException { // Skipping checks for key-value types. IFile takes care of these, but should be removed from // there as well. // How expensive are checks like these ? if (isShutdown.get()) { throw new RuntimeException("Writer already closed"); } if (spillException != null) { // Already reported as a fatalError - report to the user code throw new IOException("Exception during spill", new IOException(spillException)); } if (skipBuffers) { //special case, where we have only one partition and pipelining is disabled. // The reason outputRecordsCounter isn't updated here: // For skipBuffers case, IFile writer has the reference to // outputRecordsCounter and during its close method call, // it will update the outputRecordsCounter. writer.append(key, value); outputContext.notifyProgress(); } else { int partition = partitioner.getPartition(key, value, numPartitions); write(key, value, partition); } } @SuppressWarnings("unchecked") private void write(Object key, Object value, int partition) throws IOException { // Wrap to 4 byte (Int) boundary for metaData int mod = currentBuffer.nextPosition % INT_SIZE; int metaSkip = mod == 0 ? 0 : (INT_SIZE - mod); if ((currentBuffer.availableSize < (META_SIZE + metaSkip)) || (currentBuffer.full)) { // Move over to the next buffer. metaSkip = 0; setupNextBuffer(); } currentBuffer.nextPosition += metaSkip; int metaStart = currentBuffer.nextPosition; currentBuffer.availableSize -= (META_SIZE + metaSkip); currentBuffer.nextPosition += META_SIZE; keySerializer.serialize(key); if (currentBuffer.full) { if (metaStart == 0) { // Started writing at the start of the buffer. Write Key to disk. // Key too large for any buffer. Write entire record to disk. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try resetting the buffer to the next one, if this was not the start of a buffer, // and begin spilling the current buffer to disk if it has any records. setupNextBuffer(); write(key, value, partition); return; } } int valStart = currentBuffer.nextPosition; valSerializer.serialize(value); if (currentBuffer.full) { // Value too large for current buffer, or K-V too large for entire buffer. if (metaStart == 0) { // Key + Value too large for a single buffer. currentBuffer.reset(); writeLargeRecord(key, value, partition); return; } else { // Exceeded length on current buffer. // Try writing key+value to a new buffer - will fall back to disk if that fails. setupNextBuffer(); write(key, value, partition); return; } } // Meta-data updates int metaIndex = metaStart / INT_SIZE; int indexNext = currentBuffer.partitionPositions[partition]; currentBuffer.metaBuffer.put(metaIndex + INDEX_KEYLEN, (valStart - (metaStart + META_SIZE))); currentBuffer.metaBuffer.put(metaIndex + INDEX_VALLEN, (currentBuffer.nextPosition - valStart)); currentBuffer.metaBuffer.put(metaIndex + INDEX_NEXT, indexNext); currentBuffer.skipSize += metaSkip; // For size estimation // Update stats on number of records localOutputRecordBytesCounter += (currentBuffer.nextPosition - (metaStart + META_SIZE)); localOutputBytesWithOverheadCounter += ((currentBuffer.nextPosition - metaStart) + metaSkip); localOutputRecordsCounter++; if (localOutputRecordBytesCounter % NOTIFY_THRESHOLD == 0) { updateTezCountersAndNotify(); } currentBuffer.partitionPositions[partition] = metaStart; currentBuffer.recordsPerPartition[partition]++; currentBuffer.sizePerPartition[partition] += currentBuffer.nextPosition - (metaStart + META_SIZE); currentBuffer.numRecords++; } private void updateTezCountersAndNotify() { outputRecordBytesCounter.increment(localOutputRecordBytesCounter); outputBytesWithOverheadCounter.increment(localOutputBytesWithOverheadCounter); outputRecordsCounter.increment(localOutputRecordsCounter); outputContext.notifyProgress(); localOutputRecordBytesCounter = 0; localOutputBytesWithOverheadCounter = 0; localOutputRecordsCounter = 0; } private void setupNextBuffer() throws IOException { if (currentBuffer.numRecords == 0) { currentBuffer.reset(); } else { // Update overall stats final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": " + "Moving to next buffer. Total filled buffers: " + filledBufferCount); } updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); mayBeSpill(false); currentBuffer = getNextAvailableBuffer(); // in case spill threads are free, check if spilling is needed mayBeSpill(false); } } private void mayBeSpill(boolean shouldBlock) throws IOException { if (filledBuffers.size() >= spillLimit) { // Do not block; possible that there are more buffers scheduleSpill(shouldBlock); } } private boolean scheduleSpill(boolean block) throws IOException { if (filledBuffers.isEmpty()) { return false; } try { if (block) { availableSlots.acquire(); } else { if (!availableSlots.tryAcquire()) { // Data in filledBuffers would be spilled in subsequent iteration. return false; } } final int filledBufferCount = filledBuffers.size(); if (LOG.isDebugEnabled() || (filledBufferCount % 10) == 0) { LOG.info(destNameTrimmed + ": triggering spill. filledBuffers.size=" + filledBufferCount); } pendingSpillCount.incrementAndGet(); int spillNumber = numSpills.getAndIncrement(); ListenableFuture future = spillExecutor.submit(new SpillCallable( new ArrayList(filledBuffers), codec, spilledRecordsCounter, spillNumber)); filledBuffers.clear(); Futures.addCallback(future, new SpillCallback(spillNumber)); // Update once per buffer (instead of every record) updateTezCountersAndNotify(); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // reset interrupt status } return false; } private boolean reportPartitionStats() { return (sizePerPartition != null); } private void updateGlobalStats(WrappedBuffer buffer) { for (int i = 0; i < numPartitions; i++) { numRecordsPerPartition[i] += buffer.recordsPerPartition[i]; if (reportPartitionStats()) { sizePerPartition[i] += buffer.sizePerPartition[i]; } } } private WrappedBuffer getNextAvailableBuffer() throws IOException { if (availableBuffers.peek() == null) { if (numInitializedBuffers < numBuffers) { buffers[numInitializedBuffers] = new WrappedBuffer(numPartitions, numInitializedBuffers == numBuffers - 1 ? lastBufferSize : sizePerBuffer); numInitializedBuffers++; return buffers[numInitializedBuffers - 1]; } else { // All buffers initialized, and none available right now. Wait try { // Ensure that spills are triggered so that buffers can be released. mayBeSpill(true); return availableBuffers.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOInterruptedException("Interrupted while waiting for next buffer", e); } } } else { return availableBuffers.poll(); } } // All spills using compression for now. private class SpillCallable extends CallableWithNdc { private final List filledBuffers; private final CompressionCodec codec; private final TezCounter numRecordsCounter; private int spillIndex; private SpillPathDetails spillPathDetails; private int spillNumber; public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, SpillPathDetails spillPathDetails) { this(filledBuffers, codec, numRecordsCounter, spillPathDetails.spillIndex); Preconditions.checkArgument(spillPathDetails.outputFilePath != null, "Spill output file " + "path can not be null"); this.spillPathDetails = spillPathDetails; } public SpillCallable(List filledBuffers, CompressionCodec codec, TezCounter numRecordsCounter, int spillNumber) { this.filledBuffers = filledBuffers; this.codec = codec; this.numRecordsCounter = numRecordsCounter; this.spillNumber = spillNumber; } @Override protected SpillResult callInternal() throws IOException { // This should not be called with an empty buffer. Check before invoking. // Number of parallel spills determined by number of threads. // Last spill synchronization handled separately. SpillResult spillResult = null; if (spillPathDetails == null) { this.spillPathDetails = getSpillPathDetails(false, -1, spillNumber); this.spillIndex = spillPathDetails.spillIndex; } LOG.info("Writing spill " + spillNumber + " to " + spillPathDetails.outputFilePath.toString()); FSDataOutputStream out = rfs.create(spillPathDetails.outputFilePath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(spillPathDetails.outputFilePath, SPILL_FILE_PERMS); } TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer val = new DataInputBuffer(); long compressedLength = 0; for (int i = 0; i < numPartitions; i++) { IFile.Writer writer = null; try { long segmentStart = out.getPos(); long numRecords = 0; for (WrappedBuffer buffer : filledBuffers) { outputContext.notifyProgress(); if (buffer.partitionPositions[i] == WrappedBuffer.PARTITION_ABSENT_POSITION) { // Skip empty partition. continue; } if (writer == null) { writer = new Writer(conf, out, keyClass, valClass, codec, null, null); } numRecords += writePartition(buffer.partitionPositions[i], buffer, writer, key, val); } if (writer != null) { if (numRecordsCounter != null) { // TezCounter is not threadsafe; Since numRecordsCounter would be updated from // multiple threads, it is good to synchronize it when incrementing it for correctness. synchronized (numRecordsCounter) { numRecordsCounter.increment(numRecords); } } writer.close(); compressedLength += writer.getCompressedLength(); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); writer = null; } } finally { if (writer != null) { writer.close(); } } } key.close(); val.close(); spillResult = new SpillResult(compressedLength, this.filledBuffers); handleSpillIndex(spillPathDetails, spillRecord); LOG.info(destNameTrimmed + ": " + "Finished spill " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } return spillResult; } } private long writePartition(int pos, WrappedBuffer wrappedBuffer, Writer writer, DataInputBuffer keyBuffer, DataInputBuffer valBuffer) throws IOException { long numRecords = 0; while (pos != WrappedBuffer.PARTITION_ABSENT_POSITION) { int metaIndex = pos / INT_SIZE; int keyLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_KEYLEN); int valLength = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_VALLEN); keyBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE, keyLength); valBuffer.reset(wrappedBuffer.buffer, pos + META_SIZE + keyLength, valLength); writer.append(keyBuffer, valBuffer); numRecords++; pos = wrappedBuffer.metaBuffer.get(metaIndex + INDEX_NEXT); } return numRecords; } public static long getInitialMemoryRequirement(Configuration conf, long maxAvailableTaskMemory) { long initialMemRequestMb = conf.getInt( TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB_DEFAULT); Preconditions.checkArgument(initialMemRequestMb != 0, TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + " should be larger than 0"); long reqBytes = initialMemRequestMb << 20; LOG.info("Requested BufferSize (" + TezRuntimeConfiguration.TEZ_RUNTIME_UNORDERED_OUTPUT_BUFFER_SIZE_MB + ") : " + initialMemRequestMb); return reqBytes; } @Override public List close() throws IOException, InterruptedException { // In case there are buffers to be spilled, schedule spilling scheduleSpill(true); List eventList = Lists.newLinkedList(); isShutdown.set(true); spillLock.lock(); try { LOG.info(destNameTrimmed + ": " + "Waiting for all spills to complete : Pending : " + pendingSpillCount.get()); while (pendingSpillCount.get() != 0 && spillException == null) { spillInProgress.await(); } } finally { spillLock.unlock(); } if (spillException != null) { LOG.error(destNameTrimmed + ": " + "Error during spill, throwing"); // Assuming close will be called on the same thread as the write cleanup(); currentBuffer.cleanup(); currentBuffer = null; if (spillException instanceof IOException) { throw (IOException) spillException; } else { throw new IOException(spillException); } } else { LOG.info(destNameTrimmed + ": " + "All spills complete"); // Assuming close will be called on the same thread as the write cleanup(); List events = Lists.newLinkedList(); if (!pipelinedShuffle) { if (skipBuffers) { writer.close(); long rawLen = writer.getRawLength(); long compLen = writer.getCompressedLength(); TezIndexRecord rec = new TezIndexRecord(0, rawLen, compLen); TezSpillRecord sr = new TezSpillRecord(1); sr.putIndex(rec, 0); sr.writeToFile(finalIndexPath, conf); BitSet emptyPartitions = new BitSet(); if (outputRecordsCounter.getValue() == 0) { emptyPartitions.set(0); } if (reportPartitionStats()) { if (outputRecordsCounter.getValue() > 0) { sizePerPartition[0] = rawLen; } } cleanupCurrentBuffer(); if (outputRecordsCounter.getValue() > 0) { outputBytesWithOverheadCounter.increment(rawLen); fileOutputBytesCounter.increment(compLen + indexFileSizeEstimate); } eventList.add(generateVMEvent()); eventList.add(generateDMEvent(false, -1, false, outputContext .getUniqueIdentifier(), emptyPartitions)); return eventList; } /* 1. Final merge enabled - When lots of spills are there, mergeAll, generate events and return - If there are no existing spills, check for final spill and generate events 2. Final merge disabled - If finalSpill generated data, generate events and return - If finalSpill did not generate data, it would automatically populate events */ if (isFinalMergeEnabled) { if (numSpills.get() > 0) { mergeAll(); } else { finalSpill(); } updateTezCountersAndNotify(); eventList.add(generateVMEvent()); eventList.add(generateDMEvent()); } else { // if no data is generated, finalSpill would create VMEvent & add to finalEvents SpillResult result = finalSpill(); if (result != null) { updateTezCountersAndNotify(); // Generate vm event finalEvents.add(generateVMEvent()); // compute empty partitions based on spill result and generate DME int spillNum = numSpills.get() - 1; SpillCallback callback = new SpillCallback(spillNum); callback.computePartitionStats(result); BitSet emptyPartitions = getEmptyPartitions(callback.getRecordsPerPartition()); String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNum); Event finalEvent = generateDMEvent(true, spillNum, true, pathComponent, emptyPartitions); finalEvents.add(finalEvent); } //all events to be sent out are in finalEvents. eventList.addAll(finalEvents); } cleanupCurrentBuffer(); return eventList; } //For pipelined case, send out an event in case finalspill generated a spill file. if (finalSpill() != null) { // VertexManagerEvent is only sent at the end and thus sizePerPartition is used // for the sum of all spills. mayBeSendEventsForSpill(currentBuffer.recordsPerPartition, sizePerPartition, numSpills.get() - 1, true); } updateTezCountersAndNotify(); cleanupCurrentBuffer(); return events; } } private BitSet getEmptyPartitions(int[] recordsPerPartition) { Preconditions.checkArgument(recordsPerPartition != null, "records per partition can not be null"); BitSet emptyPartitions = new BitSet(); for (int i = 0; i < numPartitions; i++) { if (recordsPerPartition[i] == 0 ) { emptyPartitions.set(i); } } return emptyPartitions; } public boolean reportDetailedPartitionStats() { return reportPartitionStats.isPrecise(); } private Event generateVMEvent() throws IOException { return ShuffleUtils.generateVMEvent(outputContext, this.sizePerPartition, this.reportDetailedPartitionStats(), deflater.get()); } private Event generateDMEvent() throws IOException { BitSet emptyPartitions = getEmptyPartitions(numRecordsPerPartition); return generateDMEvent(false, -1, false, outputContext.getUniqueIdentifier(), emptyPartitions); } private Event generateDMEvent(boolean addSpillDetails, int spillId, boolean isLastSpill, String pathComponent, BitSet emptyPartitions) throws IOException { outputContext.notifyProgress(); DataMovementEventPayloadProto.Builder payloadBuilder = DataMovementEventPayloadProto .newBuilder(); String host = getHost(); if (emptyPartitions.cardinality() != 0) { // Empty partitions exist ByteString emptyPartitionsByteString = TezCommonUtils.compressByteArrayToByteString(TezUtilsInternal.toByteArray (emptyPartitions), deflater.get()); payloadBuilder.setEmptyPartitions(emptyPartitionsByteString); } if (emptyPartitions.cardinality() != numPartitions) { // Populate payload only if at least 1 partition has data payloadBuilder.setHost(host); payloadBuilder.setPort(getShufflePort()); payloadBuilder.setPathComponent(pathComponent); } if (addSpillDetails) { payloadBuilder.setSpillId(spillId); payloadBuilder.setLastEvent(isLastSpill); } ByteBuffer payload = payloadBuilder.build().toByteString().asReadOnlyByteBuffer(); return CompositeDataMovementEvent.create(0, numPartitions, payload); } private void cleanupCurrentBuffer() { currentBuffer.cleanup(); currentBuffer = null; } private void cleanup() { if (spillExecutor != null) { spillExecutor.shutdownNow(); } for (int i = 0; i < buffers.length; i++) { if (buffers[i] != null && buffers[i] != currentBuffer) { buffers[i].cleanup(); buffers[i] = null; } } availableBuffers.clear(); } private SpillResult finalSpill() throws IOException { if (currentBuffer.nextPosition == 0) { if (pipelinedShuffle || !isFinalMergeEnabled) { List eventList = Lists.newLinkedList(); eventList.add(ShuffleUtils.generateVMEvent(outputContext, reportPartitionStats() ? new long[numPartitions] : null, reportDetailedPartitionStats(), deflater.get())); if (localOutputRecordsCounter == 0 && outputLargeRecordsCounter.getValue() == 0) { // Should send this event (all empty partitions) only when no records are written out. BitSet emptyPartitions = new BitSet(numPartitions); emptyPartitions.flip(0, numPartitions); eventList.add(generateDMEvent(true, numSpills.get(), true, null, emptyPartitions)); } if (pipelinedShuffle) { outputContext.sendEvents(eventList); } else if (!isFinalMergeEnabled) { finalEvents.addAll(0, eventList); } } return null; } else { updateGlobalStats(currentBuffer); filledBuffers.add(currentBuffer); //setup output file and index file SpillPathDetails spillPathDetails = getSpillPathDetails(true, -1); SpillCallable spillCallable = new SpillCallable(filledBuffers, codec, null, spillPathDetails); try { SpillResult spillResult = spillCallable.call(); fileOutputBytesCounter.increment(spillResult.spillSize); fileOutputBytesCounter.increment(indexFileSizeEstimate); return spillResult; } catch (Exception ex) { throw (ex instanceof IOException) ? (IOException)ex : new IOException(ex); } } } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize) throws IOException { int spillNumber = numSpills.getAndIncrement(); return getSpillPathDetails(isFinalSpill, expectedSpillSize, spillNumber); } /** * Set up spill output file, index file details. * * @param isFinalSpill * @param expectedSpillSize * @param spillNumber * @return SpillPathDetails * @throws IOException */ private SpillPathDetails getSpillPathDetails(boolean isFinalSpill, long expectedSpillSize, int spillNumber) throws IOException { long spillSize = (expectedSpillSize < 0) ? (currentBuffer.nextPosition + numPartitions * APPROX_HEADER_LENGTH) : expectedSpillSize; Path outputFilePath = null; Path indexFilePath = null; if (!pipelinedShuffle && isFinalMergeEnabled) { if (isFinalSpill) { outputFilePath = outputFileHandler.getOutputFileForWrite(spillSize); indexFilePath = outputFileHandler.getOutputIndexFileForWrite(indexFileSizeEstimate); //Setting this for tests finalOutPath = outputFilePath; finalIndexPath = indexFilePath; } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); } } else { outputFilePath = outputFileHandler.getSpillFileForWrite(spillNumber, spillSize); indexFilePath = outputFileHandler.getSpillIndexFileForWrite(spillNumber, indexFileSizeEstimate); } return new SpillPathDetails(outputFilePath, indexFilePath, spillNumber); } private void mergeAll() throws IOException { long expectedSize = spilledSize; if (currentBuffer.nextPosition != 0) { expectedSize += currentBuffer.nextPosition - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; // Update final statistics. updateGlobalStats(currentBuffer); } SpillPathDetails spillPathDetails = getSpillPathDetails(true, expectedSize); finalIndexPath = spillPathDetails.indexFilePath; finalOutPath = spillPathDetails.outputFilePath; TezSpillRecord finalSpillRecord = new TezSpillRecord(numPartitions); DataInputBuffer keyBuffer = new DataInputBuffer(); DataInputBuffer valBuffer = new DataInputBuffer(); DataInputBuffer keyBufferIFile = new DataInputBuffer(); DataInputBuffer valBufferIFile = new DataInputBuffer(); FSDataOutputStream out = null; try { out = rfs.create(finalOutPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(finalOutPath, SPILL_FILE_PERMS); } Writer writer = null; for (int i = 0; i < numPartitions; i++) { long segmentStart = out.getPos(); if (numRecordsPerPartition[i] == 0) { LOG.info(destNameTrimmed + ": " + "Skipping partition: " + i + " in final merge since it has no records"); continue; } writer = new Writer(conf, out, keyClass, valClass, codec, null, null); try { if (currentBuffer.nextPosition != 0 && currentBuffer.partitionPositions[i] != WrappedBuffer.PARTITION_ABSENT_POSITION) { // Write current buffer. writePartition(currentBuffer.partitionPositions[i], currentBuffer, writer, keyBuffer, valBuffer); } synchronized (spillInfoList) { for (SpillInfo spillInfo : spillInfoList) { TezIndexRecord indexRecord = spillInfo.spillRecord.getIndex(i); if (indexRecord.getPartLength() == 0) { // Skip empty partitions within a spill continue; } FSDataInputStream in = rfs.open(spillInfo.outPath); in.seek(indexRecord.getStartOffset()); IFile.Reader reader = new IFile.Reader(in, indexRecord.getPartLength(), codec, null, additionalSpillBytesReadCounter, ifileReadAhead, ifileReadAheadLength, ifileBufferSize); while (reader.nextRawKey(keyBufferIFile)) { // TODO Inefficient. If spills are not compressed, a direct copy should be possible // given the current IFile format. Also exteremely inefficient for large records, // since the entire record will be read into memory. reader.nextRawValue(valBufferIFile); writer.append(keyBufferIFile, valBufferIFile); } reader.close(); } } writer.close(); fileOutputBytesCounter.increment(writer.getCompressedLength()); TezIndexRecord indexRecord = new TezIndexRecord(segmentStart, writer.getRawLength(), writer.getCompressedLength()); writer = null; finalSpillRecord.putIndex(indexRecord, i); outputContext.notifyProgress(); } finally { if (writer != null) { writer.close(); } } } } finally { if (out != null) { out.close(); } deleteIntermediateSpills(); } finalSpillRecord.writeToFile(finalIndexPath, conf); fileOutputBytesCounter.increment(indexFileSizeEstimate); LOG.info(destNameTrimmed + ": " + "Finished final spill after merging : " + numSpills.get() + " spills"); } private void deleteIntermediateSpills() { // Delete the intermediate spill files synchronized (spillInfoList) { for (SpillInfo spill : spillInfoList) { try { rfs.delete(spill.outPath, false); } catch (IOException e) { LOG.warn("Unable to delete intermediate spill " + spill.outPath, e); } } } } private void writeLargeRecord(final Object key, final Object value, final int partition) throws IOException { numAdditionalSpillsCounter.increment(1); long size = sizePerBuffer - (currentBuffer.numRecords * META_SIZE) - currentBuffer.skipSize + numPartitions * APPROX_HEADER_LENGTH; SpillPathDetails spillPathDetails = getSpillPathDetails(false, size); int spillIndex = spillPathDetails.spillIndex; FSDataOutputStream out = null; long outSize = 0; try { final TezSpillRecord spillRecord = new TezSpillRecord(numPartitions); final Path outPath = spillPathDetails.outputFilePath; out = rfs.create(outPath); if (!SPILL_FILE_PERMS.equals(SPILL_FILE_PERMS.applyUMask(FsPermission.getUMask(conf)))) { rfs.setPermission(outPath, SPILL_FILE_PERMS); } BitSet emptyPartitions = null; if (pipelinedShuffle || !isFinalMergeEnabled) { emptyPartitions = new BitSet(numPartitions); } for (int i = 0; i < numPartitions; i++) { final long recordStart = out.getPos(); if (i == partition) { spilledRecordsCounter.increment(1); Writer writer = null; try { writer = new IFile.Writer(conf, out, keyClass, valClass, codec, null, null); writer.append(key, value); outputLargeRecordsCounter.increment(1); numRecordsPerPartition[i]++; if (reportPartitionStats()) { sizePerPartition[i] += writer.getRawLength(); } writer.close(); synchronized (additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(writer.getCompressedLength()); } TezIndexRecord indexRecord = new TezIndexRecord(recordStart, writer.getRawLength(), writer.getCompressedLength()); spillRecord.putIndex(indexRecord, i); outSize = writer.getCompressedLength(); writer = null; } finally { if (writer != null) { writer.close(); } } } else { if (emptyPartitions != null) { emptyPartitions.set(i); } } } handleSpillIndex(spillPathDetails, spillRecord); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillIndex, false); LOG.info(destNameTrimmed + ": " + "Finished writing large record of size " + outSize + " to spill file " + spillIndex); if (LOG.isDebugEnabled()) { LOG.debug(destNameTrimmed + ": " + "LargeRecord Spill=" + spillIndex + ", indexPath=" + spillPathDetails.indexFilePath + ", outputPath=" + spillPathDetails.outputFilePath); } } finally { if (out != null) { out.close(); } } } private void handleSpillIndex(SpillPathDetails spillPathDetails, TezSpillRecord spillRecord) throws IOException { if (spillPathDetails.indexFilePath != null) { //write the index record spillRecord.writeToFile(spillPathDetails.indexFilePath, conf); } else { //add to cache SpillInfo spillInfo = new SpillInfo(spillRecord, spillPathDetails.outputFilePath); spillInfoList.add(spillInfo); numAdditionalSpillsCounter.increment(1); } } private class ByteArrayOutputStream extends OutputStream { private final byte[] scratch = new byte[1]; @Override public void write(int v) throws IOException { scratch[0] = (byte) v; write(scratch, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { if (currentBuffer.full) { /* no longer do anything until reset */ } else if (len > currentBuffer.availableSize) { currentBuffer.full = true; /* stop working & signal we hit the end */ } else { System.arraycopy(b, off, currentBuffer.buffer, currentBuffer.nextPosition, len); currentBuffer.nextPosition += len; currentBuffer.availableSize -= len; } } } private static class WrappedBuffer { private static final int PARTITION_ABSENT_POSITION = -1; private final int[] partitionPositions; private final int[] recordsPerPartition; // uncompressed size for each partition private final long[] sizePerPartition; private final int numPartitions; private final int size; private byte[] buffer; private IntBuffer metaBuffer; private int numRecords = 0; private int skipSize = 0; private int nextPosition = 0; private int availableSize; private boolean full = false; WrappedBuffer(int numPartitions, int size) { this.partitionPositions = new int[numPartitions]; this.recordsPerPartition = new int[numPartitions]; this.sizePerPartition = new long[numPartitions]; this.numPartitions = numPartitions; for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } size = size - (size % INT_SIZE); this.size = size; this.buffer = new byte[size]; this.metaBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()).asIntBuffer(); availableSize = size; } void reset() { for (int i = 0; i < numPartitions; i++) { this.partitionPositions[i] = PARTITION_ABSENT_POSITION; this.recordsPerPartition[i] = 0; this.sizePerPartition[i] = 0; } numRecords = 0; nextPosition = 0; skipSize = 0; availableSize = size; full = false; } void cleanup() { buffer = null; metaBuffer = null; } } private String generatePathComponent(String uniqueId, int spillNumber) { return (uniqueId + "_" + spillNumber); } private List generateEventForSpill(BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) throws IOException { List eventList = Lists.newLinkedList(); //Send out an event for consuming. String pathComponent = generatePathComponent(outputContext.getUniqueIdentifier(), spillNumber); if (isFinalUpdate) { eventList.add(ShuffleUtils.generateVMEvent(outputContext, sizePerPartition, reportDetailedPartitionStats(), deflater.get())); } Event compEvent = generateDMEvent(true, spillNumber, isFinalUpdate, pathComponent, emptyPartitions); eventList.add(compEvent); return eventList; } private void mayBeSendEventsForSpill( BitSet emptyPartitions, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { if (!pipelinedShuffle) { if (isFinalMergeEnabled) { return; } } List events = null; try { events = generateEventForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); LOG.info(destNameTrimmed + ": " + "Adding spill event for spill" + " (final update=" + isFinalUpdate + "), spillId=" + spillNumber); if (pipelinedShuffle) { //Send out an event for consuming. outputContext.sendEvents(events); } else if (!isFinalMergeEnabled) { this.finalEvents.addAll(events); } } catch (IOException e) { LOG.error(destNameTrimmed + ": " + "Error in sending pipelined events", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Error in sending events."); } } private void mayBeSendEventsForSpill(int[] recordsPerPartition, long[] sizePerPartition, int spillNumber, boolean isFinalUpdate) { BitSet emptyPartitions = getEmptyPartitions(recordsPerPartition); mayBeSendEventsForSpill(emptyPartitions, sizePerPartition, spillNumber, isFinalUpdate); } private class SpillCallback implements FutureCallback { private final int spillNumber; private int recordsPerPartition[]; private long sizePerPartition[]; SpillCallback(int spillNumber) { this.spillNumber = spillNumber; } void computePartitionStats(SpillResult result) { if (result.filledBuffers.size() == 1) { recordsPerPartition = result.filledBuffers.get(0).recordsPerPartition; sizePerPartition = result.filledBuffers.get(0).sizePerPartition; } else { recordsPerPartition = new int[numPartitions]; sizePerPartition = new long[numPartitions]; for (WrappedBuffer buffer : result.filledBuffers) { for (int i = 0; i < numPartitions; ++i) { recordsPerPartition[i] += buffer.recordsPerPartition[i]; sizePerPartition[i] += buffer.sizePerPartition[i]; } } } } int[] getRecordsPerPartition() { return recordsPerPartition; } @Override public void onSuccess(SpillResult result) { synchronized (UnorderedPartitionedKVWriter.this) { spilledSize += result.spillSize; } computePartitionStats(result); mayBeSendEventsForSpill(recordsPerPartition, sizePerPartition, spillNumber, false); try { for (WrappedBuffer buffer : result.filledBuffers) { buffer.reset(); availableBuffers.add(buffer); } } catch (Throwable e) { LOG.error(destNameTrimmed + ": Failure while attempting to reset buffer after spill", e); outputContext.reportFailure(TaskFailureType.NON_FATAL, e, "Failure while attempting to reset buffer after spill"); } if (!pipelinedShuffle && isFinalMergeEnabled) { synchronized(additionalSpillBytesWritternCounter) { additionalSpillBytesWritternCounter.increment(result.spillSize); } } else { synchronized(fileOutputBytesCounter) { fileOutputBytesCounter.increment(indexFileSizeEstimate); fileOutputBytesCounter.increment(result.spillSize); } } spillLock.lock(); try { if (pendingSpillCount.decrementAndGet() == 0) { spillInProgress.signal(); } } finally { spillLock.unlock(); availableSlots.release(); } } @Override public void onFailure(Throwable t) { // spillException setup to throw an exception back to the user. Requires synchronization. // Consider removing it in favor of having Tez kill the task LOG.error(destNameTrimmed + ": " + "Failure while spilling to disk", t); spillException = t; outputContext.reportFailure(TaskFailureType.NON_FATAL, t, "Failure while spilling to disk"); spillLock.lock(); try { spillInProgress.signal(); } finally { spillLock.unlock(); availableSlots.release(); } } } private static class SpillResult { final long spillSize; final List filledBuffers; SpillResult(long size, List filledBuffers) { this.spillSize = size; this.filledBuffers = filledBuffers; } } @VisibleForTesting static class SpillInfo { final TezSpillRecord spillRecord; final Path outPath; SpillInfo(TezSpillRecord spillRecord, Path outPath) { this.spillRecord = spillRecord; this.outPath = outPath; } } @VisibleForTesting String getHost() { return outputContext.getExecutionContext().getHostName(); } @VisibleForTesting int getShufflePort() throws IOException { String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID, TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT); ByteBuffer shuffleMetadata = outputContext .getServiceProviderMetaData(auxiliaryService); int shufflePort = ShuffleUtils.deserializeShuffleProviderMetaData(shuffleMetadata); return shufflePort; } @InterfaceAudience.Private static class SpillPathDetails { final Path indexFilePath; final Path outputFilePath; final int spillIndex; SpillPathDetails(Path outputFilePath, Path indexFilePath, int spillIndex) { this.outputFilePath = outputFilePath; this.indexFilePath = indexFilePath; this.spillIndex = spillIndex; } } } |
data class | long method, data class | t | t | t | long method | 0 | 529 | https://github.com/apache/tez/blob/d5675c332497c1ac1dedefdf91e87476b5c0d7a9/tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/writers/UnorderedPartitionedKVWriter.java/#L89-L1427 | 1 | 2 | 529 | critical | |
| 2344 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class MetricsTag implements MetricsInfo { private final MetricsInfo info; private final String value; /** * Construct the tag with name, description and value * @param info of the tag * @param value of the tag */ public MetricsTag(MetricsInfo info, String value) { this.info = checkNotNull(info, "tag info"); this.value = value; } @Override public String name() { return info.name(); } @Override public String description() { return info.description(); } /** * @return the info object of the tag */ public MetricsInfo info() { return info; } /** * Get the value of the tag * @return the value */ public String value() { return value; } @Override public boolean equals(Object obj) { if (obj instanceof MetricsTag) { final MetricsTag other = (MetricsTag) obj; return Objects.equal(info, other.info()) && Objects.equal(value, other.value()); } return false; } @Override public int hashCode() { return Objects.hashCode(info, value); } @Override public String toString() { return Objects.toStringHelper(this) .add("info", info) .add("value", value()) .toString(); } } |
data class | long method, data class | t | t | t | long method | 0 | 14186 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsTag.java/#L30-L88 | 1 | 2344 | 14186 | major | |
| 407 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | 1. long method | t | t | f | long method | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 1 | 407 | 4155 | minor | |
| 3905 | the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method, 2 Feature envy | f | f | t | 2. Feature envy | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 3905 | 10223 | minor | |
| 702 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | blob, data class | t | t | t | blob | 0 | 6697 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 1 | 702 | 6697 | critical | |
| 1030 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 1030 | 9383 | major | |
| 5499 | YES I found bad smells the bad smells are: 1. Long Method, 2. Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
feature envy | Long Method, 2 Feature Envy | t | f | t | . Long Method | 0 | 3001 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5499 | 3001 | minor | |
| 1279 | The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long method2 Feature envy | f | f | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 1279 | 10593 | minor | ||
| 2067 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultArtifact extends AbstractArtifact { public static Artifact newIvyArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, "ivy", "ivy", "xml", true); } public static Artifact newPomArtifact(ModuleRevisionId mrid, Date pubDate) { return new DefaultArtifact(mrid, pubDate, mrid.getName(), "pom", "pom", true); } public static Artifact cloneWithAnotherExt(Artifact artifact, String newExt) { return cloneWithAnotherTypeAndExt(artifact, artifact.getType(), newExt); } public static Artifact cloneWithAnotherType(Artifact artifact, String newType) { return cloneWithAnotherTypeAndExt(artifact, newType, artifact.getExt()); } public static Artifact cloneWithAnotherTypeAndExt(Artifact artifact, String newType, String newExt) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), artifact.getName(), newType, newExt, artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherName(Artifact artifact, String name) { return new DefaultArtifact(ArtifactRevisionId.newInstance(artifact.getModuleRevisionId(), name, artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } public static Artifact cloneWithAnotherMrid(Artifact artifact, ModuleRevisionId mrid) { return new DefaultArtifact(ArtifactRevisionId.newInstance(mrid, artifact.getName(), artifact.getType(), artifact.getExt(), artifact.getQualifiedExtraAttributes()), artifact.getPublicationDate(), artifact.getUrl(), artifact.isMetadata()); } private Date publicationDate; private ArtifactRevisionId arid; private URL url; private boolean isMetadata = false; public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext) { this(mrid, publicationDate, name, type, ext, null, null); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, boolean isMetadata) { this(mrid, publicationDate, name, type, ext, null, null); this.isMetadata = isMetadata; } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, Map extraAttributes) { this(mrid, publicationDate, name, type, ext, null, extraAttributes); } public DefaultArtifact(ModuleRevisionId mrid, Date publicationDate, String name, String type, String ext, URL url, Map extraAttributes) { this(ArtifactRevisionId.newInstance(mrid, name, type, ext, extraAttributes), publicationDate, url, false); } public DefaultArtifact(ArtifactRevisionId arid, Date publicationDate, URL url, boolean isMetadata) { if (arid == null) { throw new NullPointerException("null arid not allowed"); } if (publicationDate == null) { publicationDate = new Date(); } this.publicationDate = publicationDate; this.arid = arid; this.url = url; this.isMetadata = isMetadata; } public ModuleRevisionId getModuleRevisionId() { return arid.getModuleRevisionId(); } public String getName() { return arid.getName(); } public Date getPublicationDate() { return publicationDate; } public String getType() { return arid.getType(); } public String getExt() { return arid.getExt(); } public ArtifactRevisionId getId() { return arid; } public String[] getConfigurations() { return new String[0]; } public URL getUrl() { return url; } public boolean isMetadata() { return isMetadata; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 12996 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/core/module/descriptor/DefaultArtifact.java/#L30-L146 | 1 | 2067 | 12996 | minor |
| 370 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Class getPropertyEditorClass(final Object bean, final String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return PropertyUtilsBean.getInstance().getPropertyEditorClass(bean, name); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 3845 | https://github.com/apache/commons-beanutils/blob/33a067788f2a414c0b019f8d8974cc455c1982a4/src/main/java/org/apache/commons/beanutils2/PropertyUtils.java/#L458-L464 | 2 | 370 | 3845 | critical | ||
| 2081 | {"response": "YES I found bad smells", "the bad smells are": ["Long Method", "Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MemoryConsumptionTestClient { private static final Logger LOGGER = LoggerFactory.getLogger(MemoryConsumptionTestClient.class); private static final String RESULTS_FILE_ARG = "resultsFile"; private static final String JNDI_PROPERTIES_ARG = "jndiProperties"; private static final String JNDI_CONNECTION_FACTORY_ARG = "jndiConnectionFactory"; private static final String JNDI_DESTINATION_ARG = "jndiDestination"; private static final String CONNECTIONS_ARG = "connections"; private static final String SESSIONS_ARG = "sessions"; private static final String PRODUCERS_ARG = "producers"; private static final String MESSAGE_COUNT_ARG = "messagecount"; private static final String MESSAGE_SIZE_ARG = "size"; private static final String PERSISTENT_ARG = "persistent"; private static final String TIMEOUT_ARG = "timeout"; private static final String TRANSACTED_ARG = "transacted"; private static final String JMX_HOST_ARG = "jmxhost"; private static final String JMX_PORT_ARG = "jmxport"; private static final String JMX_USER_ARG = "jmxuser"; private static final String JMX_USER_PASSWORD_ARG = "jmxpassword"; private static final String RESULTS_FILE_DEFAULT = "results.csv"; private static final String JNDI_PROPERTIES_DEFAULT = "stress-test-client-qpid-jms-client-0-x.properties"; private static final String JNDI_CONNECTION_FACTORY_DEFAULT = "qpidConnectionFactory"; private static final String JNDI_DESTINATION_DEFAULT = "stressTestQueue"; private static final String CONNECTIONS_DEFAULT = "1"; private static final String SESSIONS_DEFAULT = "1"; private static final String PRODUCERS_DEFAULT = "1"; private static final String MESSAGE_COUNT_DEFAULT = "1"; private static final String MESSAGE_SIZE_DEFAULT = "256"; private static final String PERSISTENT_DEFAULT = "false"; private static final String TIMEOUT_DEFAULT = "1000"; private static final String TRANSACTED_DEFAULT = "false"; private static final String JMX_HOST_DEFAULT = "localhost"; private static final String JMX_PORT_DEFAULT = "8999"; private static final String JMX_GARBAGE_COLLECTOR_MBEAN = "gc"; public static void main(String[] args) throws Exception { Map options = new HashMap<>(); options.put(RESULTS_FILE_ARG, RESULTS_FILE_DEFAULT); options.put(JNDI_PROPERTIES_ARG, JNDI_PROPERTIES_DEFAULT); options.put(JNDI_CONNECTION_FACTORY_ARG, JNDI_CONNECTION_FACTORY_DEFAULT); options.put(JNDI_DESTINATION_ARG, JNDI_DESTINATION_DEFAULT); options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT); options.put(SESSIONS_ARG, SESSIONS_DEFAULT); options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT); options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT); options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT); options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT); options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT); options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT); options.put(JMX_HOST_ARG, JMX_HOST_DEFAULT); options.put(JMX_PORT_ARG, JMX_PORT_DEFAULT); options.put(JMX_USER_ARG, ""); options.put(JMX_USER_PASSWORD_ARG, ""); options.put(JMX_GARBAGE_COLLECTOR_MBEAN, "java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help"))) { System.out.println("arg=value options: \n" + options.keySet()); return; } parseArgumentsIntoConfig(options, args); MemoryConsumptionTestClient testClient = new MemoryConsumptionTestClient(); testClient.runTest(options); } private static void parseArgumentsIntoConfig(Map initialValues, String[] args) { for(String arg: args) { int equalPos = arg.indexOf('='); if(equalPos == -1) { throw new IllegalArgumentException("arguments must have format =: " + arg); } if(initialValues.put(arg.substring(0, equalPos), arg.substring(equalPos + 1)) == null) { throw new IllegalArgumentException("not a valid configuration property: " + arg); } } } private void runTest(Map options) throws Exception { String resultsFile = options.get(RESULTS_FILE_ARG); String jndiProperties = options.get(JNDI_PROPERTIES_ARG); String connectionFactoryString = options.get(JNDI_CONNECTION_FACTORY_ARG); int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG)); int numSessions = Integer.parseInt(options.get(SESSIONS_ARG)); int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG)); int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG)); int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG)); String queueString = options.get(JNDI_DESTINATION_ARG); int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT; long receiveTimeout = Long.parseLong(options.get(TIMEOUT_ARG)); boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG)); LOGGER.info("Using options: " + options); // Load JNDI properties Context ctx = getInitialContext(jndiProperties); final ConnectionFactory conFac = (ConnectionFactory) ctx.lookup(connectionFactoryString); Destination destination = ensureQueueCreated(queueString, conFac); Map> connectionsAndSessions = openConnectionsAndSessions(numConnections, numSessions, transacted, conFac); publish(numMessage, messageSize, numProducers, deliveryMode, destination, connectionsAndSessions); MemoryStatistic memoryStatistics = collectMemoryStatistics(options); generateCSV(memoryStatistics, numConnections, numSessions, transacted, numMessage, messageSize, numProducers, deliveryMode, resultsFile); purgeQueue(conFac, queueString, receiveTimeout); closeConnections(connectionsAndSessions.keySet()); System.exit(0); } private void generateCSV(MemoryStatistic memoryStatistics, int numConnections, int numSessions, boolean transacted, int numMessage, int messageSize, int numProducers, int deliveryMode, final String resultsFile) throws IOException { try (FileWriter writer = new FileWriter(resultsFile)) { writer.write(memoryStatistics.getHeapUsage() + "," + memoryStatistics.getDirectMemoryUsage() + "," + numConnections + "," + numSessions + "," + numProducers + "," + transacted + "," + numMessage + "," + messageSize + "," + deliveryMode + "," + toUserFriendlyName(memoryStatistics.getHeapUsage()) + "," + toUserFriendlyName(memoryStatistics.getDirectMemoryUsage()) + System.lineSeparator()); } } private void publish(int numberOfMessages, int messageSize, int numberOfProducers, int deliveryMode, Destination destination, Map> connectionsAndSessions) throws JMSException { byte[] messageBytes = generateMessage(messageSize); for (List sessions : connectionsAndSessions.values()) { for (Session session: sessions) { BytesMessage message = session.createBytesMessage(); if (messageSize > 0) { message.writeBytes(messageBytes); } for(int i = 0; i < numberOfProducers ; i++) { MessageProducer prod = session.createProducer(destination); for(int j = 0; j < numberOfMessages ; j++) { prod.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); if(session.getTransacted()) { session.commit(); } } } } } } private Map> openConnectionsAndSessions(int numConnections, int numSessions, boolean transacted, ConnectionFactory conFac) throws JMSException { Map> connectionAndSessions = new HashMap<>(); for (int i= 0; i < numConnections ; i++) { Connection connection = conFac.createConnection(); connection.setExceptionListener(jmse -> { LOGGER.error("The sample received an exception through the ExceptionListener", jmse); System.exit(1); }); List sessions = new ArrayList<>(); connectionAndSessions.put(connection, sessions); connection.start(); for (int s= 0; s < numSessions ; s++) { Session session = connection.createSession(transacted, transacted?Session.SESSION_TRANSACTED:Session.AUTO_ACKNOWLEDGE); sessions.add(session); } } return connectionAndSessions; } private Context getInitialContext(final String jndiProperties) throws IOException, NamingException { Properties properties = new Properties(); try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(jndiProperties)) { if (is != null) { properties.load(is); return new InitialContext(properties); } } System.out.printf(MemoryConsumptionTestClient.class.getSimpleName() + ": Failed to find '%s' on classpath, using fallback\n", jndiProperties); return new InitialContext(); } private Destination ensureQueueCreated(String queueURL, ConnectionFactory connectionFactory) throws JMSException { Connection connection = connectionFactory.createConnection(); Destination destination; try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueURL); MessageConsumer consumer = session.createConsumer(destination); consumer.close(); session.close(); } finally { connection.close(); } return destination; } private void closeConnections(Collection connections) throws JMSException, NamingException { for (Connection c: connections) { c.close(); } } private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException { LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueString); MessageConsumer consumer = session.createConsumer(destination); connection.start(); int count = 0; while (true) { BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout); if(msg == null) { LOGGER.debug("Received {} message(s)", count); break; } else { count++; } } consumer.close(); session.close(); connection.close(); } private MemoryStatistic collectMemoryStatistics(Map options) throws Exception { String host = options.get(JMX_HOST_ARG); String port = options.get(JMX_PORT_ARG); String user = options.get(JMX_USER_ARG); String password = options.get(JMX_USER_PASSWORD_ARG); if (!"".equals(host) && !"".equals(port) && !"".equals(user) && !"".equals(password)) { Map environment = Collections.singletonMap(JMXConnector.CREDENTIALS, new String[]{user, password}); try(JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"), environment)) { jmxConnector.connect(); final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); String gcCollectorMBeanName = options.get(JMX_GARBAGE_COLLECTOR_MBEAN); if (gcCollectorMBeanName.equals("")) { mBeanServerConnection.invoke(memoryMBean, "gc", null, null); MemoryStatistic memoryStatistics = new MemoryStatistic(); collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); return memoryStatistics; } else { ObjectName gcMBean = new ObjectName(gcCollectorMBeanName); if (mBeanServerConnection.isRegistered(gcMBean)) { return collectMemoryStatisticsAfterGCNotification(mBeanServerConnection, gcMBean); } else { Set existingGCs = mBeanServerConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=*"), null); throw new IllegalArgumentException("MBean '" +gcCollectorMBeanName + "' does not exists! Registered GC MBeans :" + existingGCs); } } } } return null; } private MemoryStatistic collectMemoryStatisticsAfterGCNotification(final MBeanServerConnection mBeanServerConnection, ObjectName gcMBean) throws MalformedObjectNameException, IOException, InstanceNotFoundException, ReflectionException, MBeanException, InterruptedException { final MemoryStatistic memoryStatistics = new MemoryStatistic(); final CountDownLatch notificationReceived = new CountDownLatch(1); final ObjectName memoryMBean = new ObjectName("java.lang:type=Memory"); mBeanServerConnection.addNotificationListener(gcMBean, (notification, handback) -> { if (notification.getType().equals("com.sun.management.gc.notification")) { CompositeData userData = (CompositeData) notification.getUserData(); try { Object gcAction = userData.get("gcAction"); Object gcCause = userData.get("gcCause"); if ("System.gc()".equals(gcCause) && String.valueOf(gcAction).contains("end of major GC")) { try { collectMemoryStatistics(memoryStatistics, mBeanServerConnection, memoryMBean); } finally { notificationReceived.countDown(); } } } catch (Exception e) { e.printStackTrace(); notificationReceived.countDown(); } } }, null, null); mBeanServerConnection.invoke(memoryMBean, "gc", null, null); if (!notificationReceived.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("GC notification was not sent in timely manner"); } return memoryStatistics; } private void collectMemoryStatistics(MemoryStatistic memoryStatistics, MBeanServerConnection mBeanServerConnection, ObjectName memoryMBean) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, IOException, MalformedObjectNameException { Object heapMemoryUsage = mBeanServerConnection.getAttribute(memoryMBean, "HeapMemoryUsage"); Object used = ((CompositeData) heapMemoryUsage).get("used"); Object directMemoryTotalCapacity = mBeanServerConnection.getAttribute(new ObjectName("java.nio:type=BufferPool,name=direct"), "TotalCapacity"); memoryStatistics.setHeapUsage(Long.parseLong(String.valueOf(used))); memoryStatistics.setDirectMemoryUsage(Long.parseLong(String.valueOf(directMemoryTotalCapacity))); } private String toUserFriendlyName(Object intValue) { long value = Long.parseLong(String.valueOf(intValue)); if (value <= 1024) { return String.valueOf(value) + "B"; } else if (value <= 1024 * 1024) { return String.valueOf(value/1024) + "kB"; } else if (value <= 1024L * 1024L * 1024L) { return String.valueOf(value/1024L/1024L) + "MB"; } else { return String.valueOf(value/1024L/1024L/1024L) + "GB"; } } private byte[] generateMessage(int messageSize) { byte[] sentBytes = new byte[messageSize]; for(int r = 0 ; r < messageSize ; r++) { sentBytes[r] = (byte) (48 + (r % 10)); } return sentBytes; } private class MemoryStatistic { private long heapUsage; private long directMemoryUsage; long getHeapUsage() { return heapUsage; } void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } long getDirectMemoryUsage() { return directMemoryUsage; } void setDirectMemoryUsage(long directMemoryUsage) { this.directMemoryUsage = directMemoryUsage; } } } |
blob | long method, blob, data class | t | t | t | long method, data class | 0 | 13072 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/tools/src/main/java/org/apache/qpid/tools/MemoryConsumptionTestClient.java/#L66-L506 | 1 | 2081 | 13072 | major | |
| 1999 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12705 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 1999 | 12705 | major | ||
| 1528 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11199 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 1528 | 11199 | minor | |
| 99 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
long method | long method | t | t | t | 0 | 1298 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 1 | 99 | 1298 | minor | ||
| 270 | {"response": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public T callWithTimeout(Callable callable, long timeoutDuration, TimeUnit timeoutUnit) throws ExecutionException { checkNotNull(callable); checkNotNull(timeoutUnit); try { return callable.call(); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } catch (Throwable e) { // It's a non-Error, non-Exception Throwable. Such classes are usually intended to extend // Exception, so we'll treat it like an Exception. throw new ExecutionException(e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2901 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java/#L49-L67 | 2 | 270 | 2901 | minor | |
| 1309 | { "YES I found bad smells": true, "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1309 | 10679 | critical | |
| 1027 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Lack of comments 4. Primitive obsession 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method 2 Duplicate code 3 Lack of comments 4 Primitive obsession 5 Feature envy | t | f | t | 0 | 9370 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1027 | 9370 | major | ||
| 1257 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | blob, data class | t | t | t | blob | 0 | 10498 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 1257 | 10498 | major | |
| 2841 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | Long method2 Feature envy | t | f | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 2 | 2841 | 1663 | minor | ||
| 2369 | {"response": "YES I found bad smells. The bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | long method | t | t | t | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 2369 | 14303 | major | ||
| 1674 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @UriParams public class Mina2Configuration implements Cloneable { @UriPath @Metadata(required = true) private String protocol; @UriPath @Metadata(required = true) private String host; @UriPath @Metadata(required = true) private int port; @UriParam(defaultValue = "true") private boolean sync = true; @UriParam(label = "codec") private boolean textline; @UriParam(label = "codec") private Mina2TextLineDelimiter textlineDelimiter; @UriParam(label = "codec") private ProtocolCodecFactory codec; @UriParam(label = "codec") private String encoding; @UriParam(defaultValue = "10000") private long writeTimeout = 10000; @UriParam(defaultValue = "30000") private long timeout = 30000; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean lazySessionCreation = true; @UriParam(label = "advanced") private boolean transferExchange; @UriParam private boolean minaLogger; @UriParam(label = "codec", defaultValue = "-1") private int encoderMaxLineLength = -1; @UriParam(label = "codec", defaultValue = "1024") private int decoderMaxLineLength = 1024; @UriParam(label = "codec") private List filters; @UriParam(label = "codec", defaultValue = "true") private boolean allowDefaultCodec = true; @UriParam private boolean disconnect; @UriParam(label = "consumer,advanced", defaultValue = "true") private boolean disconnectOnNoReply = true; @UriParam(label = "consumer,advanced", defaultValue = "WARN") private LoggingLevel noReplyLogLevel = LoggingLevel.WARN; @UriParam(label = "security") private SSLContextParameters sslContextParameters; @UriParam(label = "security", defaultValue = "true") private boolean autoStartTls = true; @UriParam(label = "advanced", defaultValue = "16") private int maximumPoolSize = 16; // 16 is the default mina setting @UriParam(label = "advanced", defaultValue = "true") private boolean orderedThreadPoolExecutor = true; @UriParam(label = "producer,advanced", defaultValue = "true") private boolean cachedAddress = true; @UriParam(label = "consumer") private boolean clientMode; /** * Returns a copy of this configuration */ public Mina2Configuration copy() { try { return (Mina2Configuration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public String getCharsetName() { if (encoding == null) { return null; } if (!Charset.isSupported(encoding)) { throw new IllegalArgumentException("The encoding: " + encoding + " is not supported"); } return Charset.forName(encoding).name(); } public String getProtocol() { return protocol; } /** * Protocol to use */ public void setProtocol(String protocol) { this.protocol = protocol; } public String getHost() { return host; } /** * Hostname to use. Use localhost or 0.0.0.0 for local server as consumer. For producer use the hostname or ip address of the remote server. */ public void setHost(String host) { this.host = host; } public int getPort() { return port; } /** * Port number */ public void setPort(int port) { this.port = port; } public boolean isSync() { return sync; } /** * Setting to set endpoint as one-way or request-response. */ public void setSync(boolean sync) { this.sync = sync; } public boolean isTextline() { return textline; } /** * Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; * if not specified or the value is false, then Object Serialization is assumed over TCP. */ public void setTextline(boolean textline) { this.textline = textline; } public Mina2TextLineDelimiter getTextlineDelimiter() { return textlineDelimiter; } /** * Only used for TCP and if textline=true. Sets the text line delimiter to use. * If none provided, Camel will use DEFAULT. * This delimiter is used to mark the end of text. */ public void setTextlineDelimiter(Mina2TextLineDelimiter textlineDelimiter) { this.textlineDelimiter = textlineDelimiter; } public ProtocolCodecFactory getCodec() { return codec; } /** * To use a custom minda codec implementation. */ public void setCodec(ProtocolCodecFactory codec) { this.codec = codec; } public String getEncoding() { return encoding; } /** * You can configure the encoding (a charset name) to use for the TCP textline codec and the UDP protocol. * If not provided, Camel will use the JVM default Charset */ public void setEncoding(String encoding) { this.encoding = encoding; } public long getWriteTimeout() { return writeTimeout; } /** * Maximum amount of time it should take to send data to the MINA session. Default is 10000 milliseconds. */ public void setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; } public long getTimeout() { return timeout; } /** * You can configure the timeout that specifies how long to wait for a response from a remote server. * The timeout unit is in milliseconds, so 60000 is 60 seconds. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isLazySessionCreation() { return lazySessionCreation; } /** * Sessions can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. */ public void setLazySessionCreation(boolean lazySessionCreation) { this.lazySessionCreation = lazySessionCreation; } public boolean isTransferExchange() { return transferExchange; } /** * Only used for TCP. You can transfer the exchange over the wire instead of just the body. * The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. * This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. */ public void setTransferExchange(boolean transferExchange) { this.transferExchange = transferExchange; } /** * To set the textline protocol encoder max line length. By default the default value of Mina itself is used which are Integer.MAX_VALUE. */ public void setEncoderMaxLineLength(int encoderMaxLineLength) { this.encoderMaxLineLength = encoderMaxLineLength; } public int getEncoderMaxLineLength() { return encoderMaxLineLength; } /** * To set the textline protocol decoder max line length. By default the default value of Mina itself is used which are 1024. */ public void setDecoderMaxLineLength(int decoderMaxLineLength) { this.decoderMaxLineLength = decoderMaxLineLength; } public int getDecoderMaxLineLength() { return decoderMaxLineLength; } public boolean isMinaLogger() { return minaLogger; } /** * You can enable the Apache MINA logging filter. Apache MINA uses slf4j logging at INFO level to log all input and output. */ public void setMinaLogger(boolean minaLogger) { this.minaLogger = minaLogger; } public List getFilters() { return filters; } /** * You can set a list of Mina IoFilters to use. */ public void setFilters(List filters) { this.filters = filters; } public boolean isDatagramProtocol() { return protocol.equals("udp"); } /** * The mina component installs a default codec if both, codec is null and textline is false. * Setting allowDefaultCodec to false prevents the mina component from installing a default codec as the first element in the filter chain. * This is useful in scenarios where another filter must be the first in the filter chain, like the SSL filter. */ public void setAllowDefaultCodec(boolean allowDefaultCodec) { this.allowDefaultCodec = allowDefaultCodec; } public boolean isAllowDefaultCodec() { return allowDefaultCodec; } public boolean isDisconnect() { return disconnect; } /** * Whether or not to disconnect(close) from Mina session right after use. Can be used for both consumer and producer. */ public void setDisconnect(boolean disconnect) { this.disconnect = disconnect; } public boolean isDisconnectOnNoReply() { return disconnectOnNoReply; } /** * If sync is enabled then this option dictates MinaConsumer if it should disconnect where there is no reply to send back. */ public void setDisconnectOnNoReply(boolean disconnectOnNoReply) { this.disconnectOnNoReply = disconnectOnNoReply; } public LoggingLevel getNoReplyLogLevel() { return noReplyLogLevel; } /** * If sync is enabled this option dictates MinaConsumer which logging level to use when logging a there is no reply to send back. */ public void setNoReplyLogLevel(LoggingLevel noReplyLogLevel) { this.noReplyLogLevel = noReplyLogLevel; } public SSLContextParameters getSslContextParameters() { return sslContextParameters; } /** * To configure SSL security. */ public void setSslContextParameters(SSLContextParameters sslContextParameters) { this.sslContextParameters = sslContextParameters; } public boolean isAutoStartTls() { return autoStartTls; } /** * Whether to auto start SSL handshake. */ public void setAutoStartTls(boolean autoStartTls) { this.autoStartTls = autoStartTls; } public int getMaximumPoolSize() { return maximumPoolSize; } /** * Number of worker threads in the worker pool for TCP and UDP */ public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public boolean isOrderedThreadPoolExecutor() { return orderedThreadPoolExecutor; } /** * Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. */ public void setOrderedThreadPoolExecutor(boolean orderedThreadPoolExecutor) { this.orderedThreadPoolExecutor = orderedThreadPoolExecutor; } /** * Whether to create the InetAddress once and reuse. Setting this to false allows to pickup DNS changes in the network. */ public void setCachedAddress(boolean shouldCacheAddress) { this.cachedAddress = shouldCacheAddress; } public boolean isCachedAddress() { return cachedAddress; } /** * If the clientMode is true, mina consumer will connect the address as a TCP client. */ public void setClientMode(boolean clientMode) { this.clientMode = clientMode; } public boolean isClientMode() { return clientMode; } // here we just shows the option setting of host, port, protocol public String getUriString() { return "mina2:" + getProtocol() + ":" + getHost() + ":" + getPort(); } } |
data class | data class | t | t | t | 0 | 11643 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-mina2/src/main/java/org/apache/camel/component/mina2/Mina2Configuration.java/#L35-L416 | 1 | 1674 | 11643 | critical | ||
| 1064 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | 1. data class | t | t | t | 0 | 9556 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 1 | 1064 | 9556 | minor | ||
| 94 | {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ServletConstants { String PAGE_HEADER = "\n" + "\n" + "\n" + " \n" + " Weblogic Monitoring Exporter\n" + "\n" + ""; // The locations of the servlets relative to the web app String MAIN_PAGE = ""; String METRICS_PAGE = "metrics"; String CONFIGURATION_PAGE = "configure"; /** The header used by a web client to send its authentication credentials. **/ String AUTHENTICATION_HEADER = "Authorization"; /** The header used by a web client to send cookies as part of a request. */ String COOKIE_HEADER = "Cookie"; // The field which defines the configuration update action String EFFECT_OPTION = "effect"; // The possible values for the effect String DEFAULT_ACTION = ServletConstants.REPLACE_ACTION; String REPLACE_ACTION = "replace"; String APPEND_ACTION = "append"; } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 1261 | https://github.com/oracle/weblogic-monitoring-exporter/blob/05f1d3c4cc797577801df0ceceb9d92fc31718e8/src/main/java/io/prometheus/wls/rest/ServletConstants.java/#L13-L41 | 1 | 94 | 1261 | minor | |
| 4111 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 10827 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 4111 | 10827 | major | ||
| 1604 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | 1 Long Method, 2 Data Class | t | f | t | 2. Data Class | 0 | 11442 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 1604 | 11442 | minor | |
| 1943 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | data class | t | t | t | 0 | 12503 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 1943 | 12503 | major | ||
| 1653 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11584 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 1653 | 11584 | minor | |
| 5537 | YES, I found bad smells. The bad smells are: 1. Long method. 2. Feature envy. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Function keyFunction, Function valueFunction) { checkNotNull(keyFunction, "keyFunction"); checkNotNull(valueFunction, "valueFunction"); return Collector.of( ImmutableSetMultimap::builder, (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)), ImmutableSetMultimap.Builder::combine, ImmutableSetMultimap.Builder::build); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6246 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/collect/ImmutableSetMultimap.java/#L86-L96 | 1 | 5537 | 6246 | minor | ||
| 110 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class PushCommand extends KeyCommand { private List values; private boolean upsert; private Direction direction; private PushCommand(@Nullable ByteBuffer key, List values, Direction direction, boolean upsert) { super(key); this.values = values; this.upsert = upsert; this.direction = direction; } /** * Creates a new {@link PushCommand} for right push ({@literal RPUSH}). * * @return a new {@link PushCommand} for right push ({@literal RPUSH}). */ public static PushCommand right() { return new PushCommand(null, Collections.emptyList(), Direction.RIGHT, true); } /** * Creates a new {@link PushCommand} for left push ({@literal LPUSH}). * * @return a new {@link PushCommand} for left push ({@literal LPUSH}). */ public static PushCommand left() { return new PushCommand(null, Collections.emptyList(), Direction.LEFT, true); } /** * Applies the {@literal value}. Constructs a new command instance with all previously configured properties. * * @param value must not be {@literal null}. * @return a new {@link PushCommand} with {@literal value} applied. */ public PushCommand value(ByteBuffer value) { Assert.notNull(value, "Value must not be null!"); return new PushCommand(null, Collections.singletonList(value), direction, upsert); } /** * Applies a {@link List} of {@literal values}. * * @param values must not be {@literal null}. * @return a new {@link PushCommand} with {@literal values} applied. */ public PushCommand values(List values) { Assert.notNull(values, "Values must not be null!"); return new PushCommand(null, new ArrayList<>(values), direction, upsert); } /** * Applies the {@literal key}. Constructs a new command instance with all previously configured properties. * * @param key must not be {@literal null}. * @return a new {@link PushCommand} with {@literal key} applied. */ public PushCommand to(ByteBuffer key) { Assert.notNull(key, "Key must not be null!"); return new PushCommand(key, values, direction, upsert); } /** * Disable upsert. Constructs a new command instance with all previously configured properties. * * @return a new {@link PushCommand} with upsert disabled. */ public PushCommand ifExists() { return new PushCommand(getKey(), values, direction, false); } /** * @return never {@literal null}. */ public List getValues() { return values; } /** * @return */ public boolean getUpsert() { return upsert; } /** * @return never {@literal null}. */ public Direction getDirection() { return direction; } } |
data class | data class | t | t | t | 0 | 1459 | https://github.com/spring-projects/spring-data-redis/blob/2eb7067e8c7e859168a281145cc46ccddb42049f/src/main/java/org/springframework/data/redis/connection/ReactiveListCommands.java/#L63-L164 | 1 | 110 | 1459 | major | ||
| 5012 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | long method | t | t | t | 0 | 13779 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 1 | 5012 | 13779 | major | ||
| 2617 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | data class | t | t | t | 0 | 15049 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 2617 | 15049 | major | ||
| 1519 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11171 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 1519 | 11171 | minor | ||
| 882 | YES I found bad smells The bad smells are: 1. Long method 2. Long method (commented section discussing subtle differences) 3. Feature envy (the if statement checking the value) 4. Duplicate code (repeated code for handling null values) 5. Long parameter list 6. Long method (within the if statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method 2 Long method (commented section discussing subtle differences) 3 Feature envy (the if statement checking the value) 4 Duplicate code (repeated code for handling null values) 5 Long parameter list 6 Long method (within the if statement) | t | f | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 882 | 8025 | minor | ||
| 5690 | YES I found bad smells the bad smells are: 1. Blob 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Blob2 Long method | t | f | t | 0 | 12064 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 1 | 5690 | 12064 | major | ||
| 1224 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 10343 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1224 | 10343 | minor | ||
| 2697 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Complex conditional statements 4. Nested loops 5. Multiple return statements 6. Lack of proper exception handling 7. Hard-coded values 8. Poorly named variables and methods 9. Mixing of concerns - the method is responsible for both weaving and writing to files 10. Inefficient usage of resources - opening and closing input/output streams for each file. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method2 Feature envy3 Complex conditional statements4 Nested loops5 Multiple return statements6 Lack of proper exception handling7 Hard-coded values8 Poorly named variables and methods9 Mixing of concerns - the method is responsible for both weaving and writing to files | t | f | t | 0 | 15320 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2697 | 15320 | major | ||
| 2065 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | 1. long method | t | t | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 2065 | 12987 | minor | ||
| 2157 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent formatting 6. Poor naming conventions 7. Inadequate commenting 8. Inefficient use of conditional statements 9. Inefficient use of variables 10. Poor use of class hierarchy 11. Mixing of concerns. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Feature envy 3 Duplicate code 4 Magic numbers 5 Inconsistent formatting 6 Poor naming conventions 7 Inadequate commenting 8 Inefficient use of conditional statements 9 Inefficient use of variables | t | f | t | 0 | 13311 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 2157 | 13311 | major | ||
| 3903 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private JPEGImageMetadataFormat() { super(JPEG.nativeImageMetadataFormatName, CHILD_POLICY_ALL); addElement("JPEGvariety", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_CHOICE); addElement("markerSequence", JPEG.nativeImageMetadataFormatName, CHILD_POLICY_SEQUENCE); addElement("app0JFIF", "JPEGvariety", CHILD_POLICY_SOME); addStreamElements("markerSequence"); addElement("app14Adobe", "markerSequence", CHILD_POLICY_EMPTY); addElement("sof", "markerSequence", 1, 4); addElement("sos", "markerSequence", 1, 4); addElement("JFXX", "app0JFIF", 1, Integer.MAX_VALUE); addElement("app0JFXX", "JFXX", CHILD_POLICY_CHOICE); addElement("app2ICC", "app0JFIF", CHILD_POLICY_EMPTY); addAttribute("app0JFIF", "majorVersion", DATATYPE_INTEGER, false, "1", "0", "255", true, true); addAttribute("app0JFIF", "minorVersion", DATATYPE_INTEGER, false, "2", "0", "255", true, true); List resUnits = new ArrayList<>(); resUnits.add("0"); resUnits.add("1"); resUnits.add("2"); addAttribute("app0JFIF", "resUnits", DATATYPE_INTEGER, false, "0", resUnits); addAttribute("app0JFIF", "Xdensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "Ydensity", DATATYPE_INTEGER, false, "1", "1", "65535", true, true); addAttribute("app0JFIF", "thumbWidth", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addAttribute("app0JFIF", "thumbHeight", DATATYPE_INTEGER, false, "0", "0", "255", true, true); addElement("JFIFthumbJPEG", "app0JFXX", CHILD_POLICY_SOME); addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY); addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY); List codes = new ArrayList<>(); codes.add("16"); // Hex 10 codes.add("17"); // Hex 11 codes.add("19"); // Hex 13 addAttribute("app0JFXX", "extensionCode", DATATYPE_INTEGER, false, null, codes); addChildElement("markerSequence", "JFIFthumbJPEG"); addAttribute("JFIFthumbPalette", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbPalette", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbWidth", DATATYPE_INTEGER, false, null, "0", "255", true, true); addAttribute("JFIFthumbRGB", "thumbHeight", DATATYPE_INTEGER, false, null, "0", "255", true, true); addObjectValue("app2ICC", ICC_Profile.class, false, null); addAttribute("app14Adobe", "version", DATATYPE_INTEGER, false, "100", "100", "255", true, true); addAttribute("app14Adobe", "flags0", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); addAttribute("app14Adobe", "flags1", DATATYPE_INTEGER, false, "0", "0", "65535", true, true); List transforms = new ArrayList<>(); transforms.add("0"); transforms.add("1"); transforms.add("2"); addAttribute("app14Adobe", "transform", DATATYPE_INTEGER, true, null, transforms); addElement("componentSpec", "sof", CHILD_POLICY_EMPTY); List procs = new ArrayList<>(); procs.add("0"); procs.add("1"); procs.add("2"); addAttribute("sof", "process", DATATYPE_INTEGER, false, null, procs); addAttribute("sof", "samplePrecision", DATATYPE_INTEGER, false, "8"); addAttribute("sof", "numLines", DATATYPE_INTEGER, false, null, "0", "65535", true, true); addAttribute("sof", "samplesPerLine", DATATYPE_INTEGER, false, null, "0", "65535", true, true); List comps = new ArrayList<>(); comps.add("1"); comps.add("2"); comps.add("3"); comps.add("4"); addAttribute("sof", "numFrameComponents", DATATYPE_INTEGER, false, null, comps); addAttribute("componentSpec", "componentId", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("componentSpec", "HsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); addAttribute("componentSpec", "VsamplingFactor", DATATYPE_INTEGER, true, null, "1", "255", true, true); List tabids = new ArrayList<>(); tabids.add("0"); tabids.add("1"); tabids.add("2"); tabids.add("3"); addAttribute("componentSpec", "QtableSelector", DATATYPE_INTEGER, true, null, tabids); addElement("scanComponentSpec", "sos", CHILD_POLICY_EMPTY); addAttribute("sos", "numScanComponents", DATATYPE_INTEGER, true, null, comps); addAttribute("sos", "startSpectralSelection", DATATYPE_INTEGER, false, "0", "0", "63", true, true); addAttribute("sos", "endSpectralSelection", DATATYPE_INTEGER, false, "63", "0", "63", true, true); addAttribute("sos", "approxHigh", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("sos", "approxLow", DATATYPE_INTEGER, false, "0", "0", "15", true, true); addAttribute("scanComponentSpec", "componentSelector", DATATYPE_INTEGER, true, null, "0", "255", true, true); addAttribute("scanComponentSpec", "dcHuffTable", DATATYPE_INTEGER, true, null, tabids); addAttribute("scanComponentSpec", "acHuffTable", DATATYPE_INTEGER, true, null, tabids); } |
long method | 1. long method | t | t | t | 0 | 10219 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java/#L43-L338 | 1 | 3903 | 10219 | critical | ||
| 2475 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getVMPassword(final GetVMPasswordCmd cmd) { final Account caller = getCaller(); final UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); ex.addProxyObject(cmd.getId().toString(), "vmId"); throw ex; } // make permission check _accountMgr.checkAccess(caller, null, true, vm); _userVmDao.loadDetails(vm); final String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { final InvalidParameterValueException ex = new InvalidParameterValueException( "No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } return password; } |
long method | long method, data class | t | t | t | data class | 0 | 14585 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/server/ManagementServerImpl.java/#L3807-L3831 | 1 | 2475 | 14585 | minor | |
| 1905 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 12371 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 1905 | 12371 | minor | ||
| 44 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Bundle[] getFragments(Bundle bundle) { if (packageAdmin == null) throw new IllegalStateException("Not started"); //$NON-NLS-1$ return packageAdmin.getFragments(bundle); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 830 | https://github.com/eclipse/packagedrone/blob/3869c1643cdc6f7cb8b26097a7b6994683b13d7e/bundles/org.eclipse.equinox.jsp.jasper/src/org/eclipse/equinox/internal/jsp/jasper/Activator.java/#L71-L76 | 2 | 44 | 830 | minor | |
| 2613 | {"result": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | 1. long method | t | t | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 2613 | 15043 | minor | ||
| 358 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SafeFileOutputStream extends FilterOutputStream { private final Path desiredFile; private Path tempFile; boolean desiredAlreadyExisted; public SafeFileOutputStream(Path file) throws IOException { this(file, tempFile(file)); } public SafeFileOutputStream(Path desiredFile, Path tempFile) throws IOException { super(Files.newOutputStream(tempFile)); this.desiredFile = desiredFile; this.tempFile = tempFile; // Some useful things to check that we preferably don't want to fail on // close() desiredAlreadyExisted = Files.exists(desiredFile); Path desiredFolder = this.desiredFile.getParent(); if (desiredAlreadyExisted) { if (!Files.isWritable(desiredFile)) { throw new FileNotFoundException("Can't write to " + desiredFile); } } else { if (!Files.exists(desiredFolder)) { throw new FileNotFoundException("Folder does not exist: " + desiredFolder); } if (!Files.isDirectory(desiredFolder)) { throw new FileNotFoundException("Not a directory: " + desiredFolder); } } if (!Files.isWritable(desiredFolder)) { throw new FileNotFoundException("Can't modify folder " + desiredFolder); } } private static Path tempFile(Path file) throws IOException { return Files.createTempFile(file.getParent(), file.getFileName() .toString(), ".tmp"); } @Override public void close() throws IOException { // If super.close fails - we leave the tempfiles behind super.close(); if (!Files.exists(tempFile)) { // Probably something went wrong before close called, // like rollback() return; } Path beforeDeletion = null; try { if (desiredAlreadyExisted) { // In case renaming goes wrong, we don't want to have already // deleted the // desired file. So we'll rename it to another temporary file // instead which // we can delete on successful rename. beforeDeletion = tempFile(desiredFile); if (!Files.deleteIfExists(beforeDeletion)) { // Should not happen, we just made it! throw new IOException("Can't delete temporary file " + beforeDeletion); } Files.move(desiredFile, beforeDeletion, StandardCopyOption.ATOMIC_MOVE); } try { Files.move(tempFile, desiredFile, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { // We'll leave our tempFiles for recovery. tempFile = null; beforeDeletion = null; if (Files.exists(desiredFile)) { // Someone else added or replaced the file afterwards, // kind-a OK return; } throw e; } } finally { if (beforeDeletion != null) { Files.deleteIfExists(beforeDeletion); } if (tempFile != null) { Files.deleteIfExists(tempFile); } } } public void rollback() throws IOException { super.close(); Files.deleteIfExists(tempFile); } } |
blob | blob, long method | t | t | t | long method | 0 | 3683 | https://github.com/apache/incubator-taverna-engine/blob/98536c6b702a0541debbb66be996455384561b54/taverna-prov/src/main/java/org/apache/taverna/prov/SafeFileOutputStream.java/#L36-L137 | 1 | 358 | 3683 | minor | |
| 1727 | private boolean isDSAPublicKeyWithoutParams(PublicKey key) { if (key.getAlgorithm().equals("DSA")) { try { key.getEncoded(); return false; } catch (NullPointerException npe) { return true; YES I found bad smells the bad smells are: 1.Long method 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | Long method2Feature envy | t | f | t | 0 | 11810 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 2 | 1727 | 11810 | minor | ||
| 2651 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Feature envy 4. Large class 5. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
data class | Long method 2 Data class3 Feature envy4 Large class5 Shotgun surgery | t | f | t | 0 | 15170 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 2 | 2651 | 15170 | critical | ||
| 1099 | {"response": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | 1. data class | t | t | t | 0 | 9827 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 1 | 1099 | 9827 | minor | ||
| 1831 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | Blob, Data Class | t | f | t | Blob | 0 | 12126 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 1 | 1831 | 12126 | minor | |
| 1834 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { Scorer scorer = scorer(context); if (scorer != null) { int newDoc = scorer.iterator().advance(doc); if (newDoc == doc) { final float freq; if (scorer instanceof BM25FScorer) { freq = ((BM25FScorer) scorer).freq(); } else { assert scorer instanceof TermScorer; freq = ((TermScorer) scorer).freq(); } final MultiNormsLeafSimScorer docScorer = new MultiNormsLeafSimScorer(simWeight, context.reader(), fieldAndWeights.values(), true); Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq); Explanation scoreExplanation = docScorer.explain(doc, freqExplanation); return Explanation.match( scoreExplanation.getValue(), "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], result of:", scoreExplanation); } } return Explanation.noMatch("no matching term"); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12132 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/sandbox/src/java/org/apache/lucene/search/BM25FQuery.java/#L308-L333 | 2 | 1834 | 12132 | minor | ||
| 4765 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | 1. long method | t | t | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 4765 | 12825 | minor | ||
| 500 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Callout implements Comparable { /** The callout number. */ private int callout = 0; /** The area Element item that generated this callout. */ private Element area = null; /** The line on which this callout occurs. */ private int line = 0; /** The column in which this callout appears. */ private int col = 0; /** The type of callout. */ private int type = 0; /** The other type of callout. */ private String otherType = null; public static final int CALS_PAIR = 1; public static final int LINE_COLUMN = 2; public static final int LINE_COLUMN_PAIR = 3; public static final int LINE_RANGE = 4; public static final int OTHER = 5; /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, int type) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = type; this.otherType = null; } /** The constructor; initialize the private data structures. */ public Callout(int callout, Element area, int line, int col, String otherType) { this.callout = callout; this.area = area; this.line = line; this.col = col; this.type = Callout.OTHER; this.otherType = otherType; } /** * The compareTo method compares this Callout with another. * * Given two Callouts, A and B, A < B if: * * * A.line < B.line, or * A.line = B.line && A.col < B.col, or * A.line = B.line && A.col = B.col && A.callout < B.callout * Otherwise, they're equal. * */ public int compareTo (Object o) { Callout c = (Callout) o; if (line == c.getLine()) { if (col > c.getColumn()) { return 1; } else if (col < c.getColumn()) { return -1; } else { if (callout < c.getCallout()) { return -1; } else if (callout > c.getCallout()) { return 1; } else { return 0; } } } else { if (line > c.getLine()) { return 1; } else { return -1; } } } /** Access the Callout's area. */ public Element getArea() { return area; } /** Access the Callout's line. */ public int getLine() { return line; } /** Access the Callout's column. */ public int getColumn() { return col; } /** Access the Callout's callout number. */ public int getCallout() { return callout; } /** Access the Callout's type. */ public int getType() { return type; } /** Access the Callout's otherType. */ public String getOtherType() { return otherType; } } |
data class | data class | t | t | t | 0 | 5070 | https://github.com/eclipse/org.aspectj/blob/370f291c359cd159c5f3f0abd6e9e53e81234a07/lib/docbook/docbook-xsl/extensions/xalan2/com/nwalsh/xalan/Callout.java/#L33-L142 | 1 | 500 | 5070 | major | ||
| 546 | {"message": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements MethodInterceptor { // ~ Instance fields // ================================================================================================ private MethodSecurityMetadataSource securityMetadataSource; // ~ Methods // ======================================================================================================== public Class getSecureObjectClass() { return MethodInvocation.class; } /** * This method should be used to enforce security on a MethodInvocation. * * @param mi The method being invoked which requires a security decision * * @return The returned value from the method invocation (possibly modified by the * {@code AfterInvocationManager}). * * @throws Throwable if any error occurs */ public Object invoke(MethodInvocation mi) throws Throwable { InterceptorStatusToken token = super.beforeInvocation(mi); Object result; try { result = mi.proceed(); } finally { super.finallyInvocation(token); } return super.afterInvocation(token, result); } public MethodSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 5550 | https://github.com/spring-projects/spring-security/blob/8dd2864dea3de5ea98637a1629debc89c29e76c0/core/src/main/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptor.java/#L40-L88 | 1 | 546 | 5550 | major |
| 1351 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10757 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 2 | 1351 | 10757 | minor | ||
| 281 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession 4. Use of magic numbers 5. Inconsistent formatting 6. Mixing of business logic and presentation (the use of LOGGER to output an error message) 7. Potential null pointer exception (if maxFiles is null) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
long method | Long method2 Feature envy3 Primitive obsession4 Use of magic numbers5 Inconsistent formatting 6 Mixing of business logic and presentation (the use of LOGGER to output an error message) 7 Potential null pointer exception (if maxFiles is null) | t | f | t | 0 | 3011 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 2 | 281 | 3011 | minor | ||
| 1516 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11165 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 2 | 1516 | 11165 | minor | ||
| 1782 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@class") @JsonSubTypes({ @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.class, name = "completed"), @JsonSubTypes.Type(value = SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics.class, name = "pending")}) public class SubtaskCheckpointStatistics { public static final String FIELD_NAME_INDEX = "index"; public static final String FIELD_NAME_CHECKPOINT_STATUS = "status"; @JsonProperty(FIELD_NAME_INDEX) private final int index; @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) private final String checkpointStatus; @JsonCreator private SubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_CHECKPOINT_STATUS) String checkpointStatus) { this.index = index; this.checkpointStatus = checkpointStatus; } public int getIndex() { return index; } public String getCheckpointStatus() { return checkpointStatus; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubtaskCheckpointStatistics that = (SubtaskCheckpointStatistics) o; return index == that.index && Objects.equals(checkpointStatus, that.checkpointStatus); } @Override public int hashCode() { return Objects.hash(index, checkpointStatus); } // --------------------------------------------------------------------------------- // Static inner classes // --------------------------------------------------------------------------------- /** * Checkpoint statistics for a completed subtask checkpoint. */ public static final class CompletedSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { public static final String FIELD_NAME_ACK_TIMESTAMP = "ack_timestamp"; public static final String FIELD_NAME_DURATION = "end_to_end_duration"; public static final String FIELD_NAME_STATE_SIZE = "state_size"; public static final String FIELD_NAME_CHECKPOINT_DURATION = "checkpoint"; public static final String FIELD_NAME_ALIGNMENT = "alignment"; @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) private final long ackTimestamp; @JsonProperty(FIELD_NAME_DURATION) private final long duration; @JsonProperty(FIELD_NAME_STATE_SIZE) private final long stateSize; @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) private final CheckpointDuration checkpointDuration; @JsonProperty(FIELD_NAME_ALIGNMENT) private final CheckpointAlignment alignment; @JsonCreator public CompletedSubtaskCheckpointStatistics( @JsonProperty(FIELD_NAME_INDEX) int index, @JsonProperty(FIELD_NAME_ACK_TIMESTAMP) long ackTimestamp, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_CHECKPOINT_DURATION) CheckpointDuration checkpointDuration, @JsonProperty(FIELD_NAME_ALIGNMENT) CheckpointAlignment alignment) { super(index, "completed"); this.ackTimestamp = ackTimestamp; this.duration = duration; this.stateSize = stateSize; this.checkpointDuration = checkpointDuration; this.alignment = alignment; } public long getAckTimestamp() { return ackTimestamp; } public long getDuration() { return duration; } public long getStateSize() { return stateSize; } public CheckpointDuration getCheckpointDuration() { return checkpointDuration; } public CheckpointAlignment getAlignment() { return alignment; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedSubtaskCheckpointStatistics that = (CompletedSubtaskCheckpointStatistics) o; return ackTimestamp == that.ackTimestamp && duration == that.duration && stateSize == that.stateSize && Objects.equals(checkpointDuration, that.checkpointDuration) && Objects.equals(alignment, that.alignment); } @Override public int hashCode() { return Objects.hash(ackTimestamp, duration, stateSize, checkpointDuration, alignment); } /** * Duration of the checkpoint. */ public static final class CheckpointDuration { public static final String FIELD_NAME_SYNC_DURATION = "sync"; public static final String FIELD_NAME_ASYNC_DURATION = "async"; @JsonProperty(FIELD_NAME_SYNC_DURATION) private final long syncDuration; @JsonProperty(FIELD_NAME_ASYNC_DURATION) private final long asyncDuration; @JsonCreator public CheckpointDuration( @JsonProperty(FIELD_NAME_SYNC_DURATION) long syncDuration, @JsonProperty(FIELD_NAME_ASYNC_DURATION) long asyncDuration) { this.syncDuration = syncDuration; this.asyncDuration = asyncDuration; } public long getSyncDuration() { return syncDuration; } public long getAsyncDuration() { return asyncDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointDuration that = (CheckpointDuration) o; return syncDuration == that.syncDuration && asyncDuration == that.asyncDuration; } @Override public int hashCode() { return Objects.hash(syncDuration, asyncDuration); } } /** * Alignment statistics of the checkpoint. */ public static final class CheckpointAlignment { public static final String FIELD_NAME_ALIGNMENT_BUFFERED = "buffered"; public static final String FIELD_NAME_ALIGNMENT_DURATION = "duration"; @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) private final long alignmentBuffered; @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) private final long alignmentDuration; @JsonCreator public CheckpointAlignment( @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_ALIGNMENT_DURATION) long alignmentDuration) { this.alignmentBuffered = alignmentBuffered; this.alignmentDuration = alignmentDuration; } public long getAlignmentBuffered() { return alignmentBuffered; } public long getAlignmentDuration() { return alignmentDuration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CheckpointAlignment that = (CheckpointAlignment) o; return alignmentBuffered == that.alignmentBuffered && alignmentDuration == that.alignmentDuration; } @Override public int hashCode() { return Objects.hash(alignmentBuffered, alignmentDuration); } } } /** * Checkpoint statistics for a pending subtask checkpoint. */ public static final class PendingSubtaskCheckpointStatistics extends SubtaskCheckpointStatistics { @JsonCreator public PendingSubtaskCheckpointStatistics(@JsonProperty(FIELD_NAME_INDEX) int index) { super(index, "pending_or_failed"); } } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 11964 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/SubtaskCheckpointStatistics.java/#L31-L283 | 1 | 1782 | 11964 | major | |
| 1150 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface MetricsIndexerSource extends BaseSource { // Metrics2 and JMX constants String METRICS_NAME = "PhoenixIndexer"; String METRICS_CONTEXT = "phoenix"; String METRICS_DESCRIPTION = "Metrics about the Phoenix Indexer"; String METRICS_JMX_CONTEXT = "RegionServer,sub=" + METRICS_NAME; String INDEX_PREPARE_TIME = "indexPrepareTime"; String INDEX_PREPARE_TIME_DESC = "Histogram for the time in milliseconds for preparing an index write"; String SLOW_INDEX_PREPARE = "slowIndexPrepareCalls"; String SLOW_INDEX_PREPARE_DESC = "The number of index preparations slower than the configured threshold"; String INDEX_WRITE_TIME = "indexWriteTime"; String INDEX_WRITE_TIME_DESC = "Histogram for the time in milliseconds for writing an index update"; String SLOW_INDEX_WRITE = "slowIndexWriteCalls"; String SLOW_INDEX_WRITE_DESC = "The number of index writes slower than the configured threshold"; String DUPLICATE_KEY_TIME = "duplicateKeyCheckTime"; String DUPLICATE_KEY_TIME_DESC = "Histogram for the time in milliseconds to handle ON DUPLICATE keywords"; String SLOW_DUPLICATE_KEY = "slowDuplicateKeyCheckCalls"; String SLOW_DUPLICATE_KEY_DESC = "The number of on duplicate key checks slower than the configured threshold"; String PRE_WAL_RESTORE_TIME = "preWALRestoreTime"; String PRE_WAL_RESTORE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's preWALRestore"; String SLOW_PRE_WAL_RESTORE = "slowPreWALRestoreCalls"; String SLOW_PRE_WAL_RESTORE_DESC = "The number of preWALRestore calls slower than the configured threshold"; String POST_PUT_TIME = "postPutTime"; String POST_PUT_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postPut"; String SLOW_POST_PUT = "slowPostPutCalls"; String SLOW_POST_PUT_DESC = "The number of postPut calls slower than the configured threshold"; String POST_DELETE_TIME = "postDeleteTime"; String POST_DELETE_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postDelete"; String SLOW_POST_DELETE = "slowPostDeleteCalls"; String SLOW_POST_DELETE_DESC = "The number of postDelete calls slower than the configured threshold"; String POST_OPEN_TIME = "postOpenTime"; String POST_OPEN_TIME_DESC = "Histogram for the time in milliseconds for Indexer's postOpen"; String SLOW_POST_OPEN = "slowPostOpenCalls"; String SLOW_POST_OPEN_DESC = "The number of postOpen calls slower than the configured threshold"; /** * Updates the index preparation time histogram (preBatchMutate). * * @param t time taken in milliseconds */ void updateIndexPrepareTime(long t); /** * Increments the number of slow calls prepare an index write. */ void incrementNumSlowIndexPrepareCalls(); /** * Updates the index write time histogram (postBatchMutate). * * @param t time taken in milliseconds */ void updateIndexWriteTime(long t); /** * Increments the number of slow calls to write to the index. */ void incrementNumSlowIndexWriteCalls(); /** * Updates the preWALRestore time histogram. * * @param t time taken in milliseconds */ void updatePreWALRestoreTime(long t); /** * Increments the number of slow preWALRestore calls. */ void incrementNumSlowPreWALRestoreCalls(); /** * Updates the postPut time histogram. * * @param t time taken in milliseconds */ void updatePostPutTime(long t); /** * Increments the number of slow postPut calls. */ void incrementNumSlowPostPutCalls(); /** * Updates the postDelete time histogram. * * @param t time taken in milliseconds */ void updatePostDeleteTime(long t); /** * Increments the number of slow postDelete calls. */ void incrementNumSlowPostDeleteCalls(); /** * Updates the postOpen time histogram. * * @param t time taken in milliseconds */ void updatePostOpenTime(long t); /** * Increments the number of slow postOpen calls. */ void incrementNumSlowPostOpenCalls(); /** * Updates the preIncrementAfterRowLock time histogram. * * @param t time taken in milliseconds */ void updateDuplicateKeyCheckTime(long t); /** * Increments the number of slow preIncrementAfteRowLock calls. */ void incrementSlowDuplicateKeyCheckCalls(); } |
data class | \n1. data class | t | t | t | 0 | 10131 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/hbase/index/metrics/MetricsIndexerSource.java/#L25-L150 | 1 | 1150 | 10131 | major | ||
| 2053 | {"output": "YES I found bad smells\nthe bad smells are:\n1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void testBug56655a() throws IOException { try (Workbook wb = _testDataProvider.createWorkbook()) { Sheet sheet = wb.createSheet(); setCellFormula(sheet, 0, 0, "B1*C1"); sheet.getRow(0).createCell(1).setCellValue("A"); setCellFormula(sheet, 1, 0, "B1*C1"); sheet.getRow(1).createCell(1).setCellValue("A"); setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultType()); assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); } } |
long method | \n1. long method | t | t | f | long method | 0 | 12903 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java/#L551-L571 | 1 | 2053 | 12903 | minor | |
| 1437 | YES, I found bad smells the bad smells are: 1. Long method 2. Duplicate code (repetitive use of "if" and "else" statements) 3. Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | Long method2 Duplicate code (repetitive use of "if" and "else" statements)3 Primitive obsession (hard-coded string literals and checks for null instead of proper data types) | t | f | t | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 2 | 1437 | 10965 | critical | ||
| 809 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface IContentEmitter { String getOutputFormat( ); void initialize( IEmitterServices service ) throws BirtException; void start( IReportContent report ) throws BirtException; void end( IReportContent report ) throws BirtException; /** * start a page * * @param page */ void startPage( IPageContent page ) throws BirtException; /** * page end * * @param page */ void endPage( IPageContent page ) throws BirtException; /** * table started * * @param table */ void startTable( ITableContent table ) throws BirtException; /** * table end */ void endTable( ITableContent table ) throws BirtException; void startTableBand( ITableBandContent band ) throws BirtException; void endTableBand( ITableBandContent band ) throws BirtException; void startRow( IRowContent row ) throws BirtException; void endRow( IRowContent row ) throws BirtException; void startCell( ICellContent cell ) throws BirtException; void endCell( ICellContent cell ) throws BirtException; void startList( IListContent list ) throws BirtException; void endList( IListContent list ) throws BirtException; void startListBand( IListBandContent listBand ) throws BirtException; void endListBand( IListBandContent listBand ) throws BirtException; void startContainer( IContainerContent container ) throws BirtException; void endContainer( IContainerContent container ) throws BirtException; void startText( ITextContent text ) throws BirtException; void startData( IDataContent data ) throws BirtException; void startLabel( ILabelContent label ) throws BirtException; void startAutoText ( IAutoTextContent autoText ) throws BirtException; void startForeign( IForeignContent foreign ) throws BirtException; void startImage( IImageContent image ) throws BirtException; void startContent( IContent content ) throws BirtException; void endContent( IContent content) throws BirtException; void startGroup( IGroupContent group ) throws BirtException; void endGroup( IGroupContent group ) throws BirtException; void startTableGroup( ITableGroupContent group ) throws BirtException; void endTableGroup( ITableGroupContent group ) throws BirtException; void startListGroup( IListGroupContent group ) throws BirtException; void endListGroup( IListGroupContent group ) throws BirtException; } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 7647 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/emitter/IContentEmitter.java/#L39-L126 | 1 | 809 | 7647 | minor | |
| 869 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 869 | 7948 | major | ||
| 1036 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 9403 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 1036 | 9403 | minor | ||
| 3053 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy (multiple references to sysDiagnostics) 4. Primitive obsession (repeated use of FormatUtils methods) 5. Switch statement (multiple entries and use of Map for sysDiagnostics properties) 6. Magic numbers (repeated use of -1) 7. Excessive parameters (sysDiagnostics and createStorageUsageDTO methods) 8. Inappropriate intimacy (accessing sysDiagnostics properties directly) 9. Lack of encapsulation (exposing internal details of SystemDiagnostics and creating StorageUsageDTO objects outside of class) 10. Data class (SystemDiagnostics, SystemDiagnosticsDTO, SystemDiagnosticsSnapshotDTO all contain only properties and getters/setters) 11. Large class (containing multiple methods and properties) 12. Primitive coupling (directly referencing sysDiagnostics rather than through an abstraction) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method2 Duplicate code3 Feature envy (multiple references to sysDiagnostics)4 Primitive obsession (repeated use of FormatUtils methods)5 Switch statement (multiple entries and use of Map for sysDiagnostics properties)6 Magic numbers (repeated use of - | t | f | t | 0 | 3501 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 3053 | 3501 | minor | ||
| 1796 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11999 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 1796 | 11999 | minor | ||
| 934 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 934 | 8390 | minor | ||
| 4238 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Success extends Try { private V value; public Success(V value) { super(); this.value = value; } @Override public Boolean isSuccess() { return true; } @Override public Boolean isFailure() { return false; } @Override public void throwException() { //log.error("Method throwException() called on a Success instance"); } @Override public V get() { return value; } @Override public Throwable getError() { return null; } } |
data class | 1. data class | t | t | t | 0 | 11157 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java/#L199-L244 | 1 | 4238 | 11157 | major | ||
| 507 | {"message":"YES I found bad smells","bad smells":["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | 1. long method | t | t | f | long method | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 1 | 507 | 5156 | minor | |
| 561 | YES, I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method | t | f | t | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 561 | 5662 | minor | ||
| 2021 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 12790 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 2021 | 12790 | major | ||
| 2268 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 13747 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2268 | 13747 | critical | |
| 26 | { "message": "YES I found bad smells", "detected_bad_smells": { "the bad smells are:": [ "1. Long Method", "2. Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConstantPartitioner implements DocumentPartitioner { /** The list with a single content type, the default one. */ private final List legalContentTypes; /** The single content type. */ private final String contentType; /** The full document length. */ private int documentLength = 0; /** Handle on the document. */ private DocumentHandle documentHandle; /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type ContentType. * * @param contentType the single content type */ public ConstantPartitioner(final String contentType) { this.contentType = contentType; this.legalContentTypes = Collections.singletonList(this.contentType); } /** * Constructor for a {@link ConstantPartitioner} that has a single partition of type {@link * DefaultPartitioner#DEFAULT_CONTENT_TYPE}. */ public ConstantPartitioner() { this(DEFAULT_CONTENT_TYPE); } @Override public void onDocumentChanged(final DocumentChangedEvent event) { final int removed = event.getLength(); int added = 0; if (event.getText() != null) { added = event.getText().length(); } final int sizeDelta = added - removed; this.documentLength += sizeDelta; } @Override public void initialize() { this.documentLength = getDocumentHandle().getDocument().getContentsCharCount(); } @Override public List getLegalContentTypes() { return legalContentTypes; } @Override public String getContentType(final int offset) { return this.contentType; } @Override public List computePartitioning(final int offset, final int length) { final TypedRegion region = getPartition(offset); return Collections.singletonList(region); } @Override public TypedRegion getPartition(final int offset) { return new TypedRegionImpl(offset, this.documentLength, this.contentType); } @Override public DocumentHandle getDocumentHandle() { return documentHandle; } @Override public void setDocumentHandle(DocumentHandle handle) { this.documentHandle = handle; } @Override public void release() {} } |
data class | the bad smells are:: 1. long method, 2. data class | t | t | t | the bad smells are:: 1. long method | 0 | 695 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/ConstantPartitioner.java/#L22-L103 | 1 | 26 | 695 | critical | |
| 127 | {"message": "YES I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | 1. data class | t | t | t | 0 | 1581 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 1 | 127 | 1581 | critical | ||
| 2127 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13223 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 2127 | 13223 | critical | ||
| 1373 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | long method, data class | t | t | t | data class | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 1 | 1373 | 10803 | critical | |
| 1719 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long Method | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 1719 | 11792 | critical | ||
| 360 | YES I found bad smells the bad smells are: 1. Long method, 2. Data class, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Long method, 2 Data class, 3 Feature envy | t | f | t | . Long method, 3. Feature envy | 0 | 3696 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 2 | 360 | 3696 | minor | |
| 2688 | { "output": "YES I found bad smells", "the bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Builder { public static boolean isForced(Map options) { return Boolean.TRUE.equals(options.get("force")); } private Properties options = new Properties(); private BuilderExtension[] extensions = new BuilderExtension[0]; private Logger logger = new NullLogger(); private ConfigurationRegistry registry; private ConfigObject configObject = null; private boolean isIncremental = false; private boolean enabledMetadata = false; private File sourceDir = null; /** * The value is a String[] containing the relative paths of all of the build * files for a given sourceDir. */ private final Map buildFilesBySourceDir = new HashMap<>(); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ private final Map> deleteFilesBySourceDir = new HashMap<>(); private final Map> buildResourcesBySourceDir = new HashMap<>(); private int buildFileCount = 0; private int deleteFileCount = 0; private int builtFileCount = 0; private int buildResourcesCount = 0; private File outputDir = null; private boolean verdict = false; private boolean includeIfUnsure = false; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ private boolean isTestsBootPath = false; private boolean noWarnIncludeIf = false; private boolean noWarnInvalidFlags = false; private boolean multipleSources = false; private boolean updateAllCopyrights = false; /** * J9 JCL Preprocessor builder constructor. Initializes the needed extensions. */ public Builder() { addExtension(new ExternalMessagesExtension()); addExtension(new MacroExtension()); addExtension(new JxeRulesExtension()); addExtension(new EclipseMetadataExtension()); addExtension(new JitAttributesExtension()); addExtension(new TagExtension()); } /** * Sets the preprocess options. * * @param options the preprocess options */ public void setOptions(Properties options) { if (options != null) { this.options.putAll(options); } this.options = options; } /** * Returns the preprocess options for this builder. * * @return the preprocess options */ public Properties getOptions() { return this.options; } /** * Adds an extension to the builder. * * @param extension the extension to add */ public void addExtension(BuilderExtension extension) { if (extension == null) { throw new NullPointerException(); } BuilderExtension[] newExtensions = new BuilderExtension[extensions.length + 1]; if (extensions.length > 0) { System.arraycopy(extensions, 0, newExtensions, 0, extensions.length); } newExtensions[newExtensions.length - 1] = extension; this.extensions = newExtensions; extension.setBuilder(this); } /** * Returns the builder extensions/ * * @return the builder extensions */ public BuilderExtension[] getExtensions() { return extensions; } /** * Returns the logger associated with this builder. * * @return the logger */ public Logger getLogger() { return logger; } /** * Sets this builder's logger. * * @param logger the new logger */ public void setLogger(Logger logger) { this.logger = logger; } /** * Sets whether the build is incremental or not. * * @param isIncremental true if the build is incremental, false otherwise */ public void setIncremental(boolean isIncremental) { this.isIncremental = isIncremental; } /** * Returns wheter or not this builder will only do an incremental build. * * @return true if the build is incremental, false otherwise */ public boolean isIncremental() { return this.isIncremental; } /** * Sets whether or not preprocessor metadata will be generated. * * @param enabledMetadata true if metadata is to be generated, * false otherwise */ public void setMetadata(boolean enabledMetadata) { this.enabledMetadata = enabledMetadata; } /** * Returns whether or not preprocessor metadata is enabled. * * @return true if metadata will be written, false otherwise */ public boolean isMetadataEnabled() { return this.enabledMetadata; } /** * Sets whether or not the preprocessor should include files that do not * have a INCLUDE-IF tag. * * @param include true if files with no INCLUDE-IF should * be included, false otherwise */ public void setIncludeIfUnsure(boolean include) { this.includeIfUnsure = include; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor is running to generate Tests Boot Path project * * @param isTestsBoot true if preprocessor is running to generate Tests Boot Path project, * false otherwise */ public void setIsTestsBoot(boolean isTestsBoot) { this.isTestsBootPath = isTestsBoot; } /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ /** * Sets whether or not the preprocessor should give warningsor errors about the files that do not * have a INCLUDE-IF tag. * * @param warning true if files with no INCLUDE-IF should * be marked with warning or error, false otherwise */ public void setNoWarnIncludeIf(boolean warning) { this.noWarnIncludeIf = warning; } /** * Sets the configuration to preprocess. * * @param config the configuration to preprocess */ public void setConfiguration(ConfigObject config) { if (config.isSet()) { System.err.println("Warning: Builder is using " + config + ", a set, not a configuration."); } this.configObject = config; this.registry = config.getRegistry(); this.outputDir = config.getOutputDir(); } /** * Returns this builder's output directory. * * @return the output directory */ public File getOutputDir() { return this.outputDir; } /** * Sets this builder's output directory. * * @param outputDir the new output directory */ public void setOutputDir(File outputDir) { if (outputDir == null) { throw new NullPointerException(); } this.outputDir = outputDir; } /** * Returns this builder's configuration source directories. * * @return the config's source dirs */ public File getSourceDir() { return this.sourceDir; } /** * Sets the proprocess job's source directory. * * @param sourceDir the source directory to preprocess */ public void setSourceDir(File sourceDir) { if (sourceDir == null) { throw new NullPointerException(); } else { this.sourceDir = sourceDir; } } /** * Set builder aware of other sources (to be used by the ExternalMessagesExtension). * * @param multipleSources true if there are other sources, false otherwise */ public void setMultipleSources(boolean multipleSources) { this.multipleSources = multipleSources; } /** * Returns whether or not the configuration that setup this builder has multiple sources. * * @return true if there are other sources, false otherwise */ public boolean hasMultipleSources() { return multipleSources; } /** * Performs the build. */ public boolean build() { //create output dir even if no file is gonna be included in preprocess getOutputDir().mkdirs(); if (validateOptions()) { computeBuildFiles(); notifyBuildBegin(); PreprocessorFactory factory = newPreprocessorFactory(); boolean force = isForced(this.options); //Ignore folders that do not exist (warning thrown in computeBuildFiles() if (sourceDir != null) { File metadataDir = new File(outputDir.getParentFile(), "jppmd"); String[] buildFiles = buildFilesBySourceDir.get(sourceDir); getLogger().log("\nPreprocessing " + sourceDir.getAbsolutePath(), 1); builtFileCount = 0; for (String buildFile : buildFiles) { File sourceFile = new File(sourceDir, buildFile); File outputFile = new File(outputDir, buildFile); File metadataFile = new File(metadataDir, buildFile + ".jppmd"); notifyBuildFileBegin(sourceFile, outputFile, buildFile); try (OutputStream metadataOutput = new PhantomOutputStream(metadataFile); OutputStream output = new PhantomOutputStream(outputFile, force)) { // configure the preprocessor and let extensions do the same JavaPreprocessor jpp; if (enabledMetadata) { jpp = factory.newPreprocessor(metadataOutput, sourceFile, output, outputFile); } else { jpp = factory.newPreprocessor(sourceFile, output); } Calendar cal = new GregorianCalendar(); if (!updateAllCopyrights) { cal.setTime(new Date(sourceFile.lastModified())); } jpp.setCopyrightYear(cal.get(Calendar.YEAR)); jpp.addValidFlags(registry.getValidFlags()); /*[PR 120411] Use a javadoc tag instead of TestBootpath preprocessor tag*/ jpp.setTestBootPath(isTestsBootPath); notifyConfigurePreprocessor(jpp); // preprocess boolean included = false; try { included = jpp.preprocess(); if (included) { builtFileCount++; } handlePreprocessorWarnings(jpp, sourceFile); } catch (Throwable t) { handlePreprocessorException(t, sourceFile); } if (!included && outputFile.exists()) { outputFile.delete(); } if (!included && metadataFile.exists()) { metadataFile.delete(); } } catch (Throwable t) { getLogger().log("Exception occured in file " + sourceFile.getAbsolutePath() + ", preprocess failed.", 3, t); handleBuildException(t); } finally { notifyBuildFileEnd(sourceFile, outputFile, buildFile); } } logger.log(builtFileCount + " of " + buildFileCount + " file(s) included in preprocess", 1); /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ List deleteFiles = deleteFilesBySourceDir.get(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { int deletedFilesCount = 0; for (String file : deleteFiles) { File deleteFile = new File(outputDir, file); if (deleteFile.exists()) { deletedFilesCount++; deleteFile.delete(); } } getLogger().log(deletedFilesCount + " of " + deleteFileCount + " file(s) deleted in preprocess from " + outputDir.getAbsolutePath(), 1); } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List buildResources = buildResourcesBySourceDir.get(sourceDir); if (buildResources != null && buildResources.size() != 0) { int copiedResourcesCount = 0; int deletedResorucesCount = 0; String outputpath; if (isTestsBootPath) { outputpath = configObject.getBootTestsOutputPath(); } else { outputpath = configObject.getTestsOutputPath(); } for (String file : buildResources) { File resource_out = new File(outputpath, file); File resource_src = new File(sourceDir, file); if (resource_src.exists()) { copyResource(resource_src, resource_out); copiedResourcesCount++; } else { resource_out.delete(); deletedResorucesCount++; } } getLogger().log("Total Build Resource Count : " + buildResourcesCount, 1); getLogger().log(" - " + copiedResourcesCount + " resource" + (copiedResourcesCount > 1 ? "s are " : " is ") + "copied to " + outputpath, 1); getLogger().log(" - " + deletedResorucesCount + " resource" + (deletedResorucesCount > 1 ? "s are " : " is ") + "deleted from " + outputpath, 1); } notifyBuildEnd(); } if (logger.getErrorCount() == 0) { if (verdict) { getLogger().log("PREPROCESS WAS SUCCESSFUL", 1); } return true; } else { if (verdict) { getLogger().log("PREPROCESS WAS NOT SUCCESSFUL", 1); } return false; } } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ public static void copyResource(File source, File destination) { destination.delete(); try { SimpleCopy.copyFile(source, destination); } catch (IOException e) { System.err.println("ERROR - Could not copy the file to destination"); System.err.println(" Source: " + source.toString()); System.err.println(" Destination: " + destination.toString()); e.printStackTrace(); } } /** * Validates the build options. */ private boolean validateOptions() { boolean isValid = true; if (configObject == null) { configObject = registry.getConfiguration(options.getProperty("config")); } this.options.putAll(configObject.getOptions()); // check for the verdict option if (options.containsKey("verdict")) { this.verdict = true; } if (options.containsKey("includeifunsure")) { setIncludeIfUnsure(true); } if (options.containsKey("nowarnincludeif")) { setNoWarnIncludeIf(true); } if (options.containsKey("nowarninvalidflags")) { this.noWarnInvalidFlags = true; } if (options.containsKey("updateallcopyrights")) { this.updateAllCopyrights = true; } // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); extension.validateOptions(this.options); } } catch (BuilderConfigurationException e) { logger.log("A configuration exception occured", Logger.SEVERITY_FATAL, e); isValid = false; } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking validateOptions() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } return isValid; } /** * Notifies the extensions that the build is beginning. */ private void notifyBuildBegin() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildBegin(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending. */ private void notifyBuildEnd() { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildEnd(); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is beginning on the specified * file. */ private void notifyBuildFileBegin(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileBegin(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileBegin() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that the build is ending on the specified file. */ private void notifyBuildFileEnd(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyBuildFileEnd(sourceFile, outputFile, relativePath); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyBuildFileEnd() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Notifies the extensions that they should configure the preprocessor. */ private void notifyConfigurePreprocessor(JavaPreprocessor preprocessor) { preprocessor.setIncludeIfUnsure(this.includeIfUnsure); preprocessor.setNoWarnIncludeIf(this.noWarnIncludeIf); // call the method for all the extensions String extensionName = ""; try { for (BuilderExtension extension : extensions) { extensionName = extension.getName(); logger.setMessageSource(extensionName); extension.notifyConfigurePreprocessor(preprocessor); logger.setMessageSource(null); } } catch (Exception e) { StringBuffer buffer = new StringBuffer("An exception occured while invoking notifyConfigurePreprocessor() for the extension \""); buffer.append(extensionName); buffer.append("\""); logger.log(buffer.toString(), Logger.SEVERITY_ERROR, e); } } /** * Handles exceptions thrown while building. */ private void handleBuildException(Throwable t) { if (t instanceof Error) { logger.log("An error occured while building", Logger.SEVERITY_FATAL, t); throw (Error) t; } else { logger.log("An exception occured while building", Logger.SEVERITY_ERROR, t); } } /** * Handles exceptions thrown by the preprocessor. */ private void handlePreprocessorException(Throwable t, File sourceFile) { if (t instanceof Error) { logger.log("An error occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_FATAL, sourceFile, t); throw (Error) t; } else { logger.log("An exception occured while invoking the preprocessor", "preprocessor", Logger.SEVERITY_ERROR, sourceFile, t); } } /** * Handles warnings generated by the preprocessor. */ private void handlePreprocessorWarnings(JavaPreprocessor jpp, File sourceFile) { if (jpp.hasWarnings()) { for (PreprocessorWarning warning : jpp.getWarnings()) { int severity = warning.shouldFail() ? Logger.SEVERITY_ERROR : Logger.SEVERITY_WARNING; /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ if (warning.getMessage().startsWith("No INCLUDE-IF") && sourceFile.getAbsolutePath().endsWith(".java") && !includeIfUnsure && !isTestsBootPath) { severity = Logger.SEVERITY_ERROR; } if (warning.getMessage().startsWith("Ignoring copyright")) { severity = Logger.SEVERITY_INFO; } logger.log(warning.getMessage(), "preprocessor", severity, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } if (!noWarnInvalidFlags) { for (PreprocessorWarning warning : jpp.getInvalidFlags()) { logger.log(warning.getMessage(), "preprocessor", Logger.SEVERITY_ERROR, sourceFile, warning.getLine(), warning.getCharstart(), warning.getCharend()); } } } /** * Determines whether the specified source file should be built. */ private boolean shouldBuild(File sourceFile, File outputFile, String relativePath) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); boolean shouldBuild = extension.shouldBuild(sourceFile, outputFile, relativePath); logger.setMessageSource(null); if (!shouldBuild) { return false; } } return true; } /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /** * Returns the deleted Files */ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getDeletedFiles(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getDeleteFiles(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ private List getBuildResources(File sourceDir) { // call the method for all the extensions for (BuilderExtension extension : extensions) { logger.setMessageSource(extension.getName()); List elements = extension.getBuildResources(sourceDir); logger.setMessageSource(null); if (elements != null) { return elements; } } return null; } /** * Creates a new PreprocessorFactory object. */ private PreprocessorFactory newPreprocessorFactory() { PreprocessorFactory factory = new PreprocessorFactory(); /*[PR 117967] idea 491: Automatically create the jars required for test bootpath*/ factory.setFlags(this.configObject.getFlagsAsArray()); factory.setRequiredIncludeFlags(this.configObject.getRequiredIncludeFlagSet()); return factory; } /** * Recursively searches the given root directory to find all files. The file * paths are returned, relative to the root directory. */ private List getFiles(File rootDirectory) { List fileList = new ArrayList<>(); File[] files = rootDirectory.listFiles(); if (files == null) { StringBuffer msg = new StringBuffer("Error reading the source directory \""); msg.append(rootDirectory.getAbsolutePath()); msg.append("\" - No Files copied"); getLogger().log(msg.toString(), 2); verdict = false; } else { getFiles(files, "", fileList); } return fileList; } /** * This is a helper function to getFiles(File); */ private static void getFiles(File[] files, String relativePath, List fileList) { for (File file : files) { if (file.isFile()) { fileList.add(relativePath + file.getName()); } else { String childRelativePath = relativePath + file.getName() + File.separator; getFiles(file.listFiles(), childRelativePath, fileList); } } } private void computeBuildFiles() { if (sourceDir.exists()) { List allFiles = getFiles(sourceDir); List buildFiles = new ArrayList<>(allFiles.size()); for (int j = 0; j < allFiles.size(); j++) { String currentFile = allFiles.get(j).toString(); if (shouldBuild(sourceDir, outputDir, currentFile)) { buildFiles.add(currentFile); } } String[] buildFilesArray = buildFiles.toArray(new String[buildFiles.size()]); buildFilesBySourceDir.put(sourceDir, buildFilesArray); buildFileCount += buildFilesArray.length; /*[PR 118220] Incremental builder is not called when file is deleted in base library*/ /*[PR 119753] classes.txt and AutoRuns are not updated when new test class is added */ List deleteFiles = getDeletedFiles(sourceDir); if (deleteFiles != null && deleteFiles.size() != 0) { deleteFileCount = deleteFiles.size(); deleteFilesBySourceDir.put(sourceDir, deleteFiles); } List buildResources = getBuildResources(sourceDir); if (buildResources != null && buildResources.size() != 0) { buildResourcesCount = buildResources.size(); buildResourcesBySourceDir.put(sourceDir, buildResources); } } else { logger.log("Error: Source directory does not exist: " + sourceDir.getAbsolutePath(), Logger.SEVERITY_ERROR, new NullPointerException()); sourceDir = null; } } /** * Returns the number of files preprocessed. * * @return the number of files preprocessed */ public int getBuildFileCount() { return buildFileCount; } } |
blob | 'Blob', 'Long Method' | t | t | f | {',B,l,o,b,',","," ",',L,o,n,g," ",M,e,t,h,o,d,'} | {',B,o,b,',","," ",',o,n,g," ",M,t,h,o,d,'} | 0 | 15283 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/sourcetools/com.ibm.jpp.preprocessor/com/ibm/jpp/om/Builder.java/#L41-L806 | 1 | 2688 | 15283 | major |
| 1916 | {"message": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | data class, long method | t | t | t | long method | 0 | 12408 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 1916 | 12408 | minor | |
| 295 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | 1. long method | t | t | t | 0 | 3109 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 1 | 295 | 3109 | minor | ||
| 2138 | { "output": "YES I found bad smells the bad smells are: 1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | 1. long method, 2. data class | t | t | f | 2. data class | long method | 0 | 13259 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 2138 | 13259 | major |
| 2040 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Long parameter list 4. Conditional complexity 5. Feature envy 6. Primitive obsession 7. Magic numbers/constants | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | Long method 2 Duplicate code 3 Long parameter list 4 Conditional complexity 5 Feature envy 6 Primitive obsession7 Magic numbers/constants | t | f | t | 0 | 12850 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 2 | 2040 | 12850 | major | ||
| 5638 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Long method", "2. Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
long method | 1. long method, 2. feature envy | t | t | f | 2. feature envy | long method | 0 | 10869 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 2 | 5638 | 10869 | major |
| 2851 | YES I found bad smells the bad smells are: 1. Unused import 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String getDisplayName() { return AssignmentsTestLanguageLanguage.INSTANCE.getDisplayName(); } |
feature envy | Unused import 2 Feature Envy | t | f | t | 0 | 1807 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.core.idea.tests/src-gen/org/eclipse/xtext/parser/assignments/idea/highlighting/AssignmentsTestLanguageBaseColorSettingsPage.java/#L13-L16 | 2 | 2851 | 1807 | major | ||
| 609 | YES I found bad smells 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 609 | 6124 | minor | ||
| 1719 | YES I found bad smells the bad smells are: 1. Long method 2. Complex implementation 3. Overly nested conditional statements 4. Lack of proper commenting/documentation 5. Feature envy (multiple lines of code that should be in a separate object or method) 6. Use of magic numbers 7. Lack of proper error handling 8. Unnecessary use of system calls/arrays 9. Inefficient use of loops/iterations 10. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method 2 Complex implementation 3 Overly nested conditional statements 4 Lack of proper commenting/documentation 5 Feature envy (multiple lines of code that should be in a separate object or method) 6 Use of magic numbers 7 Lack of proper error handling 8 Unnecessary use of system calls/arrays 9 Inefficient use of loops/iterations | t | f | t | 0 | 11792 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 1719 | 11792 | critical | ||
| 217 | {"message": "YES I found bad smells the bad smells are: 1.Long method, 2.Magic number, 3.Data class"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | 1.long method, 2.magic number, 3.data class | t | t | t | 1.long method, 2.magic number | 0 | 2368 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 2 | 217 | 2368 | major | |
| 589 | { "message": "YES I found bad smells", "detected_bad_smells": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | long method | t | t | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 1 | 589 | 5882 | minor | ||
| 5407 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 15185 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 5407 | 15185 | major | |
| 1246 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1246 | 10421 | minor | |
| 2041 | {"message": "YES, I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection igniteInstanceNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void addIgniteInstance(String igniteInstanceName) { igniteInstanceNames.add(igniteInstanceName); } /** * Remove Ignite instance name. * * @param igniteInstanceName Ignite instance name. */ public void removeIgniteInstance(String igniteInstanceName) { igniteInstanceNames.remove(igniteInstanceName); } /** * Returns {@code true} if data contains the specified * Ignite instance name. * * @param igniteInstanceName Ignite instance name. * @return {@code true} if data contains the specified Ignite instance name. */ public boolean containsIgniteInstance(String igniteInstanceName) { return igniteInstanceNames.contains(igniteInstanceName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } } |
data class | blob, data class, long method | t | t | f | blob, long method | data class | 0 | 12853 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java/#L2796-L2872 | 1 | 2041 | 12853 | minor |
| 1238 | { "response": "YES I found bad smells", "detected_smells": [ "the bad smells are:", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | the bad smells are:, 2. feature envy | t | t | t | the bad smells are: | 0 | 10397 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1238 | 10397 | minor | |
| 2628 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | data class, long method | t | t | t | long method | 0 | 15087 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 2628 | 15087 | minor | |
| 1793 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11996 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 1793 | 11996 | critical | |
| 2237 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
feature envy | Feature envy | t | f | t | 0 | 13612 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 2 | 2237 | 13612 | minor | ||
| 1063 | { "message": "YES, I found bad smells", "detected_bad_smells": [ { "1": "Long Method" }, { "2": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | 1: long method, 2: data class | t | t | t | 2: data class | 0 | 9551 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1063 | 9551 | minor | |
| 653 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 653 | 6389 | critical | ||
| 1062 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | data class | t | t | t | 0 | 9545 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 1 | 1062 | 9545 | minor | ||
| 2423 | YES I found bad smells the bad smells are: 1. Data class 2. Dead code - unused imports and variables 3. Magic numbers - the numbers 3472875885259250934 and 0 are used without explanation 4. Shotgun surgery - several methods directly and indirectly manipulate multiple fields and properties of the class, making it difficult to maintain/change in the future 5. Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | Data class2 Dead code - unused imports and variables3 Magic numbers - the numbers 3472875885259250934 and 0 are used without explanation4 Shotgun surgery - several methods directly and indirectly manipulate multiple fields and properties of the class, making it difficult to maintain/change in the future5 Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | t | f | t | making it difficult to maintain/change in the future5. Message chain - the chain of method calls in the equals() method can be simplified for better readability and maintainability | 0 | 14441 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 2 | 2423 | 14441 | major | |
| 2517 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14699 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 1 | 2517 | 14699 | major | ||
| 3795 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | 1. long method | t | t | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 3795 | 9593 | minor | ||
| 4487 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static List> getFacilityContactMechValueMaps(Delegator delegator, String facilityId, boolean showOld, String contactMechTypeId) { List> facilityContactMechValueMaps = new LinkedList>(); List allFacilityContactMechs = null; try { List tempCol = EntityQuery.use(delegator).from("FacilityContactMech").where("facilityId", facilityId).queryList(); if (contactMechTypeId != null) { List tempColTemp = new LinkedList(); for (GenericValue partyContactMech: tempCol) { GenericValue contactMech = delegator.getRelatedOne("ContactMech", partyContactMech, false); if (contactMech != null && contactMechTypeId.equals(contactMech.getString("contactMechTypeId"))) { tempColTemp.add(partyContactMech); } } tempCol = tempColTemp; } if (!showOld) tempCol = EntityUtil.filterByDate(tempCol, true); allFacilityContactMechs = tempCol; } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (allFacilityContactMechs == null) return facilityContactMechValueMaps; for (GenericValue facilityContactMech: allFacilityContactMechs) { GenericValue contactMech = null; try { contactMech = facilityContactMech.getRelatedOne("ContactMech", false); } catch (GenericEntityException e) { Debug.logWarning(e, module); } if (contactMech != null) { Map facilityContactMechValueMap = new HashMap(); facilityContactMechValueMaps.add(facilityContactMechValueMap); facilityContactMechValueMap.put("contactMech", contactMech); facilityContactMechValueMap.put("facilityContactMech", facilityContactMech); try { facilityContactMechValueMap.put("contactMechType", contactMech.getRelatedOne("ContactMechType", true)); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { List facilityContactMechPurposes = facilityContactMech.getRelated("FacilityContactMechPurpose", null, null, false); if (!showOld) facilityContactMechPurposes = EntityUtil.filterByDate(facilityContactMechPurposes, true); facilityContactMechValueMap.put("facilityContactMechPurposes", facilityContactMechPurposes); } catch (GenericEntityException e) { Debug.logWarning(e, module); } try { if ("POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("postalAddress", contactMech.getRelatedOne("PostalAddress", false)); } else if ("TELECOM_NUMBER".equals(contactMech.getString("contactMechTypeId"))) { facilityContactMechValueMap.put("telecomNumber", contactMech.getRelatedOne("TelecomNumber", false)); } } catch (GenericEntityException e) { Debug.logWarning(e, module); } } } return facilityContactMechValueMaps; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11883 | https://github.com/apache/ofbiz/blob/7ba7f3c2e16df6c8db0d8114e124957199cea1ff/applications/party/src/main/java/org/apache/ofbiz/party/contact/ContactMechWorker.java/#L129-L198 | 2 | 4487 | 11883 | major | ||
| 2573 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method | t | f | t | 0 | 14908 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 2573 | 14908 | minor | ||
| 656 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Problems { /** Represents compiler fatal errors. */ public enum FatalError { FILE_NOT_FOUND("File '%s' not found.", 1), UNKNOWN_INPUT_TYPE("Cannot recognize input type for file '%s'.", 1), OUTPUT_LOCATION("Output location '%s' must be a directory or .zip file.", 1), CANNOT_EXTRACT_ZIP("Cannot extract zip '%s'.", 1), CANNOT_CREATE_ZIP("Cannot create zip '%s': %s.", 2), CANNOT_CLOSE_ZIP("Cannot close zip: %s.", 1), CANNOT_CREATE_TEMP_DIR("Cannot create temporary directory: %s.", 1), CANNOT_OPEN_FILE("Cannot open file: %s.", 1), CANNOT_WRITE_FILE("Cannot write file: %s.", 1), CANNOT_COPY_FILE("Cannot copy file: %s.", 1), PACKAGE_INFO_PARSE("Resource '%s' was found but it failed to parse.", 1), CLASS_PATH_URL("Class path entry '%s' is not a valid url.", 1), GWT_INCOMPATIBLE_FOUND_IN_COMPILE( "@GwtIncompatible annotations found in %s " + "Please run this library through the @GwtIncompatible stripper tool.", 1), ; // used for customized message. private final String message; // number of arguments the message takes. private final int numberOfArguments; FatalError(String message, int numberOfArguments) { this.message = message; this.numberOfArguments = numberOfArguments; } public String getMessage() { return message; } private int getNumberOfArguments() { return numberOfArguments; } } /** Represents the severity of the problem */ public enum Severity { ERROR("Error"), WARNING("Warning"), INFO("Info"); Severity(String messagePrefix) { this.messagePrefix = messagePrefix; } private final String messagePrefix; public String getMessagePrefix() { return messagePrefix; } } private final Multimap problemsBySeverity = LinkedHashMultimap.create(); public void fatal(FatalError fatalError, Object... args) { checkArgument(fatalError.getNumberOfArguments() == args.length); problemsBySeverity.put( Severity.ERROR, "Error: " + String.format(fatalError.getMessage(), args)); abort(); } public void error(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.ERROR, sourcePosition, detailMessage, args); } public void error(int lineNumber, String filePath, String detailMessage, Object... args) { problem(Severity.ERROR, lineNumber, filePath, detailMessage, args); } public void warning(SourcePosition sourcePosition, String detailMessage, Object... args) { problem(Severity.WARNING, sourcePosition, detailMessage, args); } private void problem( Severity severity, SourcePosition sourcePosition, String detailMessage, Object... args) { problem( severity, // SourcePosition lines are 0 based. sourcePosition.getStartFilePosition().getLine() + 1, sourcePosition.getFilePath(), detailMessage, args); } private void problem( Severity severity, int lineNumber, String filePath, String detailMessage, Object... args) { String message = args.length == 0 ? detailMessage : String.format(detailMessage, args); problemsBySeverity.put( severity, String.format( "%s:%s:%s: %s", severity.getMessagePrefix(), filePath.substring(filePath.lastIndexOf('/') + 1), lineNumber, message)); } public void error(String detailMessage, Object... args) { problemsBySeverity.put(Severity.ERROR, "Error: " + String.format(detailMessage, args)); } public void warning(String detailMessage, Object... args) { problemsBySeverity.put(Severity.WARNING, String.format(detailMessage, args)); } public void info(String detailMessage, Object... args) { problemsBySeverity.put(Severity.INFO, String.format(detailMessage, args)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintStream output) { return reportAndGetExitCode(new PrintWriter(output, true)); } /** Prints all problems to provided output and returns the exit code. */ public int reportAndGetExitCode(PrintWriter output) { for (Map.Entry severityMessagePair : problemsBySeverity.entries()) { output.println(severityMessagePair.getValue()); } if (hasErrors() || hasWarnings()) { output.printf( "%d error(s), %d warning(s).\n", problemsBySeverity.get(Severity.ERROR).size(), problemsBySeverity.get(Severity.WARNING).size()); } return hasErrors() ? 1 : 0; } public boolean hasWarnings() { return problemsBySeverity.containsKey(Severity.WARNING); } public boolean hasErrors() { return problemsBySeverity.containsKey(Severity.ERROR); } public boolean hasProblems() { return !problemsBySeverity.isEmpty(); } public void abortIfHasErrors() { if (hasErrors()) { abort(); } } public void abort() { throw new Exit(this); } public List getErrors() { return getMessages(Severity.ERROR); } public List getWarnings() { return getMessages(Severity.WARNING); } public List getInfoMessages() { return getMessages(Severity.INFO); } public List getMessages() { return getMessages(EnumSet.allOf(Severity.class)); } private List getMessages(Severity severity) { return getMessages(Collections.singleton(severity)); } private List getMessages(Collection severities) { return problemsBySeverity .entries() .stream() .filter(e -> severities.contains(e.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); } /** * Exit is thrown to signal that a System.exit should be performed at a higher level. * * Note: It should never be caught except on the top level. */ public static class Exit extends java.lang.Error { private final Problems problems; private Exit(Problems problems) { this.problems = problems; } public Problems getProblems() { return problems; } } } |
data class | data class, long method | t | t | t | long method | 0 | 6405 | https://github.com/google/j2cl/blob/f233ebf547cce390cf87ce346ed82e0512f4fbe1/transpiler/java/com/google/j2cl/common/Problems.java/#L32-L234 | 1 | 656 | 6405 | critical | |
| 4011 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10604 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 4011 | 10604 | minor | ||
| 483 | YES I found bad smells the bad smells are: 1. Long method 2. Lack of abstraction/encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method2 Lack of abstraction/encapsulation | t | f | t | 0 | 4713 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 483 | 4713 | minor | ||
| 928 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicAttributeSensor extends BasicSensor implements AttributeSensor { private static final long serialVersionUID = -2493209215974820300L; private final SensorPersistenceMode persistence; public BasicAttributeSensor(Class type, String name) { this(type, name, name); } public BasicAttributeSensor(Class type, String name, String description) { this(type, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(TypeToken typeToken, String name) { this(typeToken, name, name); } public BasicAttributeSensor(TypeToken typeToken, String name, String description) { this(typeToken, name, description, SensorPersistenceMode.REQUIRED); } public BasicAttributeSensor(Class type, String name, String description, SensorPersistenceMode persistence) { this(type, null, name, description, persistence); } public BasicAttributeSensor(TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { this(null, typeToken, name, description, persistence); } public BasicAttributeSensor(Class type, TypeToken typeToken, String name, String description, SensorPersistenceMode persistence) { super(type, typeToken, name, description); this.persistence = checkNotNull(persistence, "persistence"); } @Override public SensorPersistenceMode getPersistenceMode() { // persistence could be null if deserializing state written by an old version; in which case default to 'required' return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; } } |
data class | data class | t | t | t | 0 | 8330 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/core/src/main/java/org/apache/brooklyn/core/sensor/BasicAttributeSensor.java/#L31-L67 | 1 | 928 | 8330 | minor | ||
| 643 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (multiple if-else statements) 4. Inappropriate type (using String instead of a constant or boolean) 5. Inconsistent formatting (missing spaces before and after braces) 6. Poor naming of variables (sel, sql, buf) 7. Tight coupling (method is heavily reliant on external methods and objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Long method2 Feature envy3 Duplicate code (multiple if-else statements)4 Inappropriate type (using String instead of a constant or boolean)5 Inconsistent formatting (missing spaces before and after braces)6 Poor naming of variables (sel, sql, buf)7 Tight coupling (method is heavily reliant on external methods and objects) | t | f | t | sql, buf)7. Tight coupling (method is heavily reliant on external methods and objects) | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 643 | 6354 | critical | |
| 406 | YES, I found bad smells. 1. Feature envy 2. Long method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void delete(UserInfo user) throws CoreException { JSONObject sites = getSites(user); if (!sites.has(getId())) { //nothing to do, site does not exist return; } sites.remove(getId()); user.setProperty(SiteConfigurationConstants.KEY_SITE_CONFIGURATIONS, sites.toString()); OrionConfiguration.getMetaStore().updateUser(user); } |
feature envy | Feature envy2 Long method | t | f | t | 0 | 4144 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/SiteInfo.java/#L150-L159 | 2 | 406 | 4144 | major | ||
| 814 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Named @RequestScoped public class UserUpdateBean { private String name; private String surname; private int age; private String userName; private String password; private @Inject @Default UserController controller; private @Inject @Default SessionTracker tracker; public UserUpdateBean() { } public String showInfo() { //Just show how can access session webbeans User user = this.controller.getUser(tracker.getUser().getId()); setName(user.getName()); setSurname(user.getSurname()); setAge(user.getAge()); setUserName(user.getUserName()); setPassword(user.getPassword()); return "toUpdatePage"; } public String clear() { setName(""); setSurname(""); setAge(0); setUserName(""); setPassword(""); return null; } public String update() { this.controller.updateUserInfo(tracker.getUser().getId(), name, surname, age, userName, password); JSFUtility.addInfoMessage("Personal information is succesfully updated.", ""); return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname the surname to set */ public void setSurname(String surname) { this.surname = surname; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } } |
data class | data class | t | t | t | 0 | 7656 | https://github.com/apache/openwebbeans/blob/7831798861478a035c9e9dcca151b5a67e4a28a3/samples/reservation/src/main/java/org/apache/webbeans/reservation/beans/user/UserUpdateBean.java/#L31-L169 | 1 | 814 | 7656 | critical | ||
| 1644 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method | t | f | t | 0 | 11558 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1644 | 11558 | major | ||
| 1443 | YES, I found bad smells the bad smells are: 1. Long Method, 2. Duplicated Code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long Method, 2 Duplicated Code | t | f | t | 2. Duplicated Code | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 1443 | 10977 | minor | |
| 1287 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10613 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 2 | 1287 | 10613 | minor | ||
| 53 | { "response": "YES, I found bad smells", "bad_smells": [ "1. Long method", "2. Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout) throws IOException { final ProxyParams proxyParams = prepareProxyParams(); return executeUrl(httpMethod, url, httpHeaders, content, contentType, timeout, proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword, proxyParams.nonProxyHosts); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 879 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/io/org.eclipse.smarthome.io.net/src/main/java/org/eclipse/smarthome/io/net/http/HttpUtil.java/#L127-L133 | 2 | 53 | 879 | major | |
| 999 | "YES, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy." | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method, 2 Feature envy" | t | f | t | 2. Feature envy." | 0 | 9162 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 999 | 9162 | major | |
| 5601 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String sendMessage(final Map headers, final int type, final String body, boolean durable, final String user, final String password) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.sendMessage(this, null, headers, type, body, durable, user, "****"); } try { return sendMessage(addressInfo.getName(), server, headers, type, body, durable, user, password); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10170 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/AddressControlImpl.java/#L347-L363 | 1 | 5601 | 10170 | minor | ||
| 5571 | YES I found bad smells the bad smells are: Blob, Data Class, Feature Envy, Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
feature envy | Blob, Data Class, Feature Envy, Long Method | t | f | t | Blob, Data Class, Long Method | 0 | 8188 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 1 | 5571 | 8188 | minor | |
| 1413 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | data class | t | t | t | 0 | 10905 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1413 | 10905 | major | ||
| 1660 | { "message": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long Method | t | f | t | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 1660 | 11609 | minor | ||
| 1739 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private synchronized Map getResourceBundleEntries(final Bundle bundle) { String file = (String) bundle.getHeaders().get(Constants.BUNDLE_LOCALIZATION); if (file == null) { file = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } // remove leading slash if (file.startsWith("/")) //$NON-NLS-1$ { file = file.substring(1); } // split path and base name int slash = file.lastIndexOf('/'); String fileName = file.substring(slash + 1); String path = (slash <= 0) ? "/" : file.substring(0, slash); //$NON-NLS-1$ HashMap resourceBundleEntries = new HashMap(); Enumeration locales = bundle.findEntries(path, fileName + "*.properties", false); //$NON-NLS-1$ if (locales != null) { while (locales.hasMoreElements()) { URL entry = (URL) locales.nextElement(); // calculate the key String entryPath = entry.getPath(); final int start = entryPath.lastIndexOf('/') + 1 + fileName.length(); // path, // slash // and // base // name final int end = entryPath.length() - 11; // .properties suffix entryPath = entryPath.substring(start, end); // the default language is "name.properties" thus the entry // path is empty and must default to "_"+DEFAULT_LOCALE if (entryPath.length() == 0) { entryPath = "_" + DEFAULT_LOCALE; //$NON-NLS-1$ } // only add this entry, if the "language" is not provided // by the main bundle or an earlier bound fragment if (!resourceBundleEntries.containsKey(entryPath)) { resourceBundleEntries.put(entryPath, entry); } } } return resourceBundleEntries; } |
long method | Long Method | t | f | t | 0 | 11836 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/inventory/src/main/java/org/apache/felix/inventory/impl/webconsole/ResourceBundleManager.java/#L134-L189 | 1 | 1739 | 11836 | major | ||
| 1733 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (the use of CellarSupport class multiple times within the method) 3. Lack of exception handling 4. Magic numbers (use of numbers without explanation within the code) 5. Poorly named variables (e.g. "in", "out", "pid", etc.) 6. Lack of comments/ documentation 7. Duplicated code 8. Inconsistent formatting (e.g. use of tabs and spaces) 9. Use of System.out.println statements for error handling 10. Mixing display mode and edit mode within the same method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long method2 Feature envy (the use of CellarSupport class multiple times within the method)3 Lack of exception handling 4 Magic numbers (use of numbers without explanation within the code)5 Poorly named variables (eg "in", "out", "pid", etc)6 Lack of comments/ documentation7 Duplicated code 8 Inconsistent formatting (eg use of tabs and spaces) 9 Use of Systemoutprintln statements for error handling | t | f | t | "out", "pid", etc.)6. Lack of comments/ documentation7. Duplicated code 8. Inconsistent formatting (e.g. use of tabs and spaces) 9. Use of System.out.println statements for error handling | 0 | 11822 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1733 | 11822 | major | |
| 2221 | Yes I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13553 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 2 | 2221 | 13553 | major | ||
| 2253 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | data class | t | t | t | 0 | 13685 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 2253 | 13685 | major | ||
| 1861 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12222 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 1861 | 12222 | minor | ||
| 1171 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Immutable private static final class NumberLiteralNode extends PrimitiveLiteralNode { private static final long serialVersionUID = 1L; private final Type type = numberGetType(value); private NumberLiteralNode(final long token, final int finish, final Number value) { super(Token.recast(token, TokenType.DECIMAL), finish, value); } private NumberLiteralNode(final NumberLiteralNode literalNode) { super(literalNode); } private static Type numberGetType(final Number number) { if (number instanceof Integer) { return Type.INT; } else if (number instanceof Double) { return Type.NUMBER; } else { assert false; } return null; } @Override public Type getType() { return type; } @Override public Type getWidestOperationType() { return getType(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10196 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java/#L373-L409 | 1 | 1171 | 10196 | minor | |
| 717 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, 10. Use of compound assignments for complex logic. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void emitStackMove(CompilationResultBuilder crb, AArch64MacroAssembler masm, AllocatableValue result, Value input) { try (ScratchRegister r1 = masm.getScratchRegister()) { try (ScratchRegister r2 = masm.getScratchRegister()) { Register rscratch1 = r1.getRegister(); Register rscratch2 = r2.getRegister(); // use the slot kind to define the operand size PlatformKind kind = input.getPlatformKind(); final int size = kind.getSizeInBytes() * Byte.SIZE; // Always perform stack -> stack copies through integer registers crb.blockComment("[stack -> stack copy]"); AArch64Address src = loadStackSlotAddress(crb, masm, asStackSlot(input), rscratch2); masm.ldr(size, rscratch1, src); AArch64Address dst = loadStackSlotAddress(crb, masm, asStackSlot(result), rscratch2); masm.str(size, rscratch1, dst); } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Use of try-with-resources blocks for unrelated classes, 5 Inconsistent indentation, 6 Lack of comments and explanatory code, 7 Lack of meaningful variable and method names, 8 Duplicate code in try-with-resources blocks, 9 Use of multiple nested try-catch blocks, | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Use of try-with-resources blocks for unrelated classes, 5. Inconsistent indentation, 6. Lack of comments and explanatory code, 7. Lack of meaningful variable and method names, 8. Duplicate code in try-with-resources blocks, 9. Use of multiple nested try-catch blocks, | 0 | 6826 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir.aarch64/src/org/graalvm/compiler/lir/aarch64/AArch64Move.java/#L393-L410 | 2 | 717 | 6826 | minor | |
| 2080 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | data class, long method | t | t | t | long method | 0 | 13068 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 1 | 2080 | 13068 | major | |
| 1660 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | Long method2 Feature envy: The method uses multiple different objects from external classes, indicating a possible violation of encapsulation and dependency issues 3 Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent 4 Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging | t | f | t | indicating a possible violation of encapsulation and dependency issues. 3. Inconsistent formatting: The use of different indentation and spacing throughout the code makes it less readable and inconsistent. 4. Inadequate exception handling: The method only logs the exception and returns null, which could lead to unexpected behavior and difficulty in debugging. | 0 | 11609 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 2 | 1660 | 11609 | minor | |
| 551 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5564 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 551 | 5564 | major | ||
| 2540 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14774 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2540 | 14774 | major | ||
| 1444 | { "output": "YES I found bad smells the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | 1. data class | t | t | t | 0 | 10980 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 1444 | 10980 | major | ||
| 2066 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | data class, long method | t | t | t | long method | 0 | 12994 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 1 | 2066 | 12994 | minor | |
| 1432 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method, 2Magic numbers, 3Duplicate code, 4Long parameter list, 5 Feature envy, 6 Poor variable naming | t | f | t | 2.Magic numbers, 3.Duplicate code, 4.Long parameter list, 5. Feature envy, 6. Poor variable naming | 0 | 10956 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 1432 | 10956 | minor | |
| 2040 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | long method, blob | t | t | t | blob | 0 | 12850 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 2040 | 12850 | major | |
| 2555 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MessageComponent extends UIOutput { // ------------------------------------------------------------ Constructors /** * Create a new {@link MessageComponent} with default properties. */ public MessageComponent() { super(); setRendererType("org.apache.struts.faces.Message"); } // ------------------------------------------------------ Instance Variables /** * MessageResources attribute key to use for message lookup. */ private String bundle = null; /** * Flag indicating whether output should be filtered. */ private boolean filter = true; private boolean filterSet = false; /** * Message key to use for message lookup. */ private String key = null; /** * CSS style(s) to be rendered for this component. */ private String style = null; /** * CSS style class(es) to be rendered for this component. */ private String styleClass = null; // ---------------------------------------------------- Component Properties /** * Return the MessageResources key. */ public String getBundle() { ValueBinding vb = getValueBinding("bundle"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return bundle; } } /** * Set the MessageResources key. * * @param bundle The new key */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Return the component family to which this component belongs. */ public String getFamily() { return "org.apache.struts.faces.Message"; } /** * Return a flag indicating whether filtering should take place. */ public boolean isFilter() { if (filterSet) { return filter; } ValueBinding vb = getValueBinding("filter"); if (vb != null) { Boolean value = (Boolean) vb.getValue(getFacesContext()); if (null == value) { return filter; } return value.booleanValue(); } else { return filter; } } /** * Set the flag indicating that the output value should be filtered. * * @param filter The new filter flag */ public void setFilter(boolean filter) { this.filter = filter; this.filterSet = true; } /** * Return the message key. */ public String getKey() { ValueBinding vb = getValueBinding("key"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return key; } } /** * Set the message key. * * @param key The new key */ public void setKey(String key) { this.key = key; } /** * Return the CSS style(s) to be rendered for this component. */ public String getStyle() { ValueBinding vb = getValueBinding("style"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return style; } } /** * Set the CSS style(s) to be rendered for this component. * * @param style The new CSS style(s) */ public void setStyle(String style) { this.style = style; } /** * Return the CSS style class(es) to be rendered for this component. */ public String getStyleClass() { ValueBinding vb = getValueBinding("styleClass"); if (vb != null) { return (String) vb.getValue(getFacesContext()); } else { return styleClass; } } /** * Set the CSS style class(es) to be rendered for this component. * * @param styleClass The new CSS style class(es) */ public void setStyleClass(String styleClass) { this.styleClass = styleClass; } // ---------------------------------------------------- StateManager Methods /** * Restore the state of this component. * * @param context FacesContext for the current request * @param state State object from which to restore our state */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); bundle = (String) values[1]; filter = ((Boolean) values[2]).booleanValue(); filterSet = ((Boolean) values[3]).booleanValue(); key = (String) values[4]; style = (String) values[5]; styleClass = (String) values[6]; } /** * Save the state of this component. * * @param context FacesContext for the current request */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = super.saveState(context); values[1] = bundle; values[2] = filter ? Boolean.TRUE : Boolean.FALSE; values[3] = filterSet ? Boolean.TRUE : Boolean.FALSE; values[4] = key; values[5] = style; values[6] = styleClass; return values; } } |
data class | data class | t | t | t | 0 | 14825 | https://github.com/apache/struts1/blob/02c9ff7485b1900515c6e0b32ed54ea46dd97d51/faces/src/main/java/org/apache/struts/faces/component/MessageComponent.java/#L35-L285 | 1 | 2555 | 14825 | major | ||
| 1581 | YES I found bad smells the bad smells are: 1. Long method 2. Inappropriate coupling 3. Feature envy 4. Duplicated code 5. Magic numbers 6. Dead code 7. Misplaced responsibility 8. Inconsistent naming 9. Data class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | Long method 2 Inappropriate coupling 3 Feature envy 4 Duplicated code 5 Magic numbers 6 Dead code 7 Misplaced responsibility 8 Inconsistent naming 9 Data class | t | f | t | 0 | 11362 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 2 | 1581 | 11362 | critical | ||
| 1913 | { "response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 12402 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 1913 | 12402 | minor | |
| 1265 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | data class, long method | t | t | t | long method | 0 | 10541 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 1 | 1265 | 10541 | minor | |
| 2424 | {"response": "YES I found bad smells the bad smells are: 1. Blob, 2. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 14443 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 2424 | 14443 | critical | |
| 2351 | { "output": "YES I found bad smells", "the bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListKeysResult extends com.ibm.cloud.objectstorage.AmazonWebServiceResult implements Serializable, Cloneable { /** * * A list of keys. * */ private com.ibm.cloud.objectstorage.internal.SdkInternalList keys; /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * */ private String nextMarker; /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * */ private Boolean truncated; /** * * A list of keys. * * * @return A list of keys. */ public java.util.List getKeys() { if (keys == null) { keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(); } return keys; } /** * * A list of keys. * * * @param keys * A list of keys. */ public void setKeys(java.util.Collection keys) { if (keys == null) { this.keys = null; return; } this.keys = new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys); } /** * * A list of keys. * * * NOTE: This method appends the values to the existing list (if any). Use * {@link #setKeys(java.util.Collection)} or {@link #withKeys(java.util.Collection)} if you want to override the * existing values. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(KeyListEntry... keys) { if (this.keys == null) { setKeys(new com.ibm.cloud.objectstorage.internal.SdkInternalList(keys.length)); } for (KeyListEntry ele : keys) { this.keys.add(ele); } return this; } /** * * A list of keys. * * * @param keys * A list of keys. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withKeys(java.util.Collection keys) { setKeys(keys); return this; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @return When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. */ public String getNextMarker() { return this.nextMarker; } /** * * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * * * @param nextMarker * When Truncated is true, this element is present and contains the value to use for the * Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withNextMarker(String nextMarker) { setNextMarker(nextMarker); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public void setTruncated(Boolean truncated) { this.truncated = truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean getTruncated() { return this.truncated; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @param truncated * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListKeysResult withTruncated(Boolean truncated) { setTruncated(truncated); return this; } /** * * A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in this * response to the Marker parameter in a subsequent request. * * * @return A flag that indicates whether there are more items in the list. When this value is true, the list in this * response is truncated. To retrieve more items, pass the value of the NextMarker element in * this response to the Marker parameter in a subsequent request. */ public Boolean isTruncated() { return this.truncated; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKeys() != null) sb.append("Keys: ").append(getKeys()).append(","); if (getNextMarker() != null) sb.append("NextMarker: ").append(getNextMarker()).append(","); if (getTruncated() != null) sb.append("Truncated: ").append(getTruncated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListKeysResult == false) return false; ListKeysResult other = (ListKeysResult) obj; if (other.getKeys() == null ^ this.getKeys() == null) return false; if (other.getKeys() != null && other.getKeys().equals(this.getKeys()) == false) return false; if (other.getNextMarker() == null ^ this.getNextMarker() == null) return false; if (other.getNextMarker() != null && other.getNextMarker().equals(this.getNextMarker()) == false) return false; if (other.getTruncated() == null ^ this.getTruncated() == null) return false; if (other.getTruncated() != null && other.getTruncated().equals(this.getTruncated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKeys() == null) ? 0 : getKeys().hashCode()); hashCode = prime * hashCode + ((getNextMarker() == null) ? 0 : getNextMarker().hashCode()); hashCode = prime * hashCode + ((getTruncated() == null) ? 0 : getTruncated().hashCode()); return hashCode; } @Override public ListKeysResult clone() { try { return (ListKeysResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } } |
data class | data class | t | t | t | 0 | 14219 | https://github.com/IBM/ibm-cos-sdk-java/blob/d6b03864c15c622ce439e39f20ab41a77dc1cc83/ibm-cos-java-sdk-kms/src/main/java/com/ibm/cloud/objectstorage/services/kms/model/ListKeysResult.java/#L22-L300 | 1 | 2351 | 14219 | minor | ||
| 1984 | { "NO, I did not find any bad smell" : "Blob" , "Data Class" : [], "Feature Envy" : "YES I found bad smells", "the bad smells are" : [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage |
blob | "Blob" , "Data Class" | t | f | t | "Data Class" | 0 | 12647 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 | 1 | 1984 | 12647 | major | |
| 1361 | YES I found bad smells The bad smells are:1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Predicate isUnix() { return new Predicate() { @Override public boolean apply(OperatingSystem os) { if (os.getFamily() != null) { switch (os.getFamily()) { case WINDOWS: return false; } } for (String toMatch : searchStrings(os)) if (toMatch != null && toMatch.toLowerCase().indexOf("windows") != -1) return false; return true; } @Override public String toString() { return "isUnix()"; } }; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10778 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java/#L38-L59 | 2 | 1361 | 10778 | minor | |
| 943 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SimpleMessage implements Message { private final MessageId messageId; private final String subType; private final String mediaType; private final SharedInputStream content; private final int bodyStartOctet; private final Date internalDate; private final long size; private final Long textualLineCount; private final List properties; private final List attachments; public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties, List attachments) { this.messageId = messageId; this.subType = subType; this.mediaType = mediaType; this.content = content; this.bodyStartOctet = bodyStartOctet; this.internalDate = internalDate; this.size = size; this.textualLineCount = textualLineCount; this.properties = properties; this.attachments = attachments; } public SimpleMessage(MessageId messageId, SharedInputStream content, long size, Date internalDate, String subType, String mediaType, int bodyStartOctet, Long textualLineCount, List properties) { this(messageId, content, size, internalDate, subType, mediaType, bodyStartOctet, textualLineCount, properties, ImmutableList.of()); } @Override public MessageId getMessageId() { return messageId; } @Override public Date getInternalDate() { return internalDate; } @Override public InputStream getBodyContent() throws IOException { return content.newStream(bodyStartOctet, -1); } @Override public String getMediaType() { return mediaType; } @Override public String getSubType() { return subType; } @Override public long getBodyOctets() { return getFullContentOctets() - bodyStartOctet; } @Override public long getHeaderOctets() { return bodyStartOctet; } @Override public long getFullContentOctets() { return size; } @Override public Long getTextualLineCount() { return textualLineCount; } @Override public InputStream getHeaderContent() throws IOException { long headerEnd = bodyStartOctet; if (headerEnd < 0) { headerEnd = 0; } return content.newStream(0, headerEnd); } @Override public InputStream getFullContent() throws IOException { return content.newStream(0, -1); } @Override public List getProperties() { return properties; } @Override public List getAttachments() { return attachments; } } |
blob | blob, long method | t | t | t | long method | 0 | 8473 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/mail/model/impl/SimpleMessage.java/#L35-L133 | 1 | 943 | 8473 | minor | |
| 2012 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12754 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 2 | 2012 | 12754 | critical | ||
| 1045 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | long method | t | t | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 1 | 1045 | 9454 | major | ||
| 2105 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | Feature envy2 Long method | t | f | t | 0 | 13169 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 2 | 2105 | 13169 | minor | ||
| 61 | { "answer": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } |
long method | 1. long method | t | t | t | 0 | 1020 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/util/ParsableByteArray.java/#L473-L485 | 1 | 61 | 1020 | minor | ||
| 1552 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | Long Method | t | f | t | 0 | 11269 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 1 | 1552 | 11269 | major | ||
| 2532 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 2532 | 14744 | minor | |
| 1743 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ImportImpl extends ElementImpl implements Import { /** * The default value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected static final String IMPORTED_NAMESPACE_EDEFAULT = null; /** * The cached value of the '{@link #getImportedNamespace() Imported Namespace}' attribute. * * * @see #getImportedNamespace() * @generated * @ordered */ protected String importedNamespace = IMPORTED_NAMESPACE_EDEFAULT; /** * * * @generated */ protected ImportImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return SDomainPackage.Literals.IMPORT; } /** * * * @generated */ public String getImportedNamespace() { return importedNamespace; } /** * * * @generated */ public void setImportedNamespace(String newImportedNamespace) { String oldImportedNamespace = importedNamespace; importedNamespace = newImportedNamespace; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SDomainPackage.IMPORT__IMPORTED_NAMESPACE, oldImportedNamespace, importedNamespace)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return getImportedNamespace(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: setImportedNamespace(IMPORTED_NAMESPACE_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SDomainPackage.IMPORT__IMPORTED_NAMESPACE: return IMPORTED_NAMESPACE_EDEFAULT == null ? importedNamespace != null : !IMPORTED_NAMESPACE_EDEFAULT.equals(importedNamespace); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (importedNamespace: "); result.append(importedNamespace); result.append(')'); return result.toString(); } } //ImportImpl |
data class | Data Class | t | f | t | 0 | 11846 | https://github.com/eclipse/xtext-idea/blob/3aa1424ae35f1942dd7c3a457057006f9131de5e/org.eclipse.xtext.idea.sdomain/src-gen/org/eclipse/xtext/idea/sdomain/sDomain/impl/ImportImpl.java/#L34-L183 | 1 | 1743 | 11846 | minor | ||
| 1493 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void write(String baseDir) throws IOException { String filename = baseDir + File.separator + CharacterDefinition.class.getName().replace('.', File.separatorChar) + CharacterDefinition.FILENAME_SUFFIX; new File(filename).getParentFile().mkdirs(); OutputStream os = new FileOutputStream(filename); try { os = new BufferedOutputStream(os); final DataOutput out = new OutputStreamDataOutput(os); CodecUtil.writeHeader(out, CharacterDefinition.HEADER, CharacterDefinition.VERSION); out.writeBytes(characterCategoryMap, 0, characterCategoryMap.length); for (int i = 0; i < CharacterDefinition.CLASS_COUNT; i++) { final byte b = (byte) ( (invokeMap[i] ? 0x01 : 0x00) | (groupMap[i] ? 0x02 : 0x00) ); out.writeByte(b); } } finally { os.close(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11121 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/CharacterDefinitionWriter.java/#L73-L93 | 2 | 1493 | 11121 | minor | ||
| 631 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6291 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 2 | 631 | 6291 | minor | ||
| 2307 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14085 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 2307 | 14085 | major | |
| 4085 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void send(byte[] data, int length, InetAddress host, int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10772 | https://github.com/apache/commons-net/blob/fb7aae4c64f7d2bf6dced00c49c3ffc428b2d572/src/main/java/org/apache/commons/net/discard/DiscardUDPClient.java/#L63-L71 | 2 | 4085 | 10772 | major | |
| 2057 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement public class Book { private int id; private String name; public Book() {} public Book(int bookId, String name) { this.id = bookId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 12952 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/examples/mp-rest-client/src/main/java/org/superbiz/rest/Book.java/#L22-L50 | 1 | 2057 | 12952 | major | ||
| 1662 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TypeRefWithoutModifiersElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.ts.TypeExpressions.TypeRefWithoutModifiers"); private final Alternatives cAlternatives = (Alternatives)rule.eContents().get(1); private final Group cGroup_0 = (Group)cAlternatives.eContents().get(0); private final Alternatives cAlternatives_0_0 = (Alternatives)cGroup_0.eContents().get(0); private final RuleCall cParameterizedTypeRefParserRuleCall_0_0_0 = (RuleCall)cAlternatives_0_0.eContents().get(0); private final RuleCall cThisTypeRefParserRuleCall_0_0_1 = (RuleCall)cAlternatives_0_0.eContents().get(1); private final Assignment cDynamicAssignment_0_1 = (Assignment)cGroup_0.eContents().get(1); private final Keyword cDynamicPlusSignKeyword_0_1_0 = (Keyword)cDynamicAssignment_0_1.eContents().get(0); private final RuleCall cTypeTypeRefParserRuleCall_1 = (RuleCall)cAlternatives.eContents().get(1); private final RuleCall cFunctionTypeExpressionOLDParserRuleCall_2 = (RuleCall)cAlternatives.eContents().get(2); private final RuleCall cUnionTypeExpressionOLDParserRuleCall_3 = (RuleCall)cAlternatives.eContents().get(3); private final RuleCall cIntersectionTypeExpressionOLDParserRuleCall_4 = (RuleCall)cAlternatives.eContents().get(4); //TypeRefWithoutModifiers StaticBaseTypeRef: // (ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef // | FunctionTypeExpressionOLD // | UnionTypeExpressionOLD // | IntersectionTypeExpressionOLD; @Override public ParserRule getRule() { return rule; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? | TypeTypeRef | FunctionTypeExpressionOLD | UnionTypeExpressionOLD //| IntersectionTypeExpressionOLD public Alternatives getAlternatives() { return cAlternatives; } //(ParameterizedTypeRef | ThisTypeRef) => dynamic?='+'? public Group getGroup_0() { return cGroup_0; } //ParameterizedTypeRef | ThisTypeRef public Alternatives getAlternatives_0_0() { return cAlternatives_0_0; } //ParameterizedTypeRef public RuleCall getParameterizedTypeRefParserRuleCall_0_0_0() { return cParameterizedTypeRefParserRuleCall_0_0_0; } //ThisTypeRef public RuleCall getThisTypeRefParserRuleCall_0_0_1() { return cThisTypeRefParserRuleCall_0_0_1; } //=> dynamic?='+'? public Assignment getDynamicAssignment_0_1() { return cDynamicAssignment_0_1; } //'+' public Keyword getDynamicPlusSignKeyword_0_1_0() { return cDynamicPlusSignKeyword_0_1_0; } //TypeTypeRef public RuleCall getTypeTypeRefParserRuleCall_1() { return cTypeTypeRefParserRuleCall_1; } //FunctionTypeExpressionOLD public RuleCall getFunctionTypeExpressionOLDParserRuleCall_2() { return cFunctionTypeExpressionOLDParserRuleCall_2; } //UnionTypeExpressionOLD public RuleCall getUnionTypeExpressionOLDParserRuleCall_3() { return cUnionTypeExpressionOLDParserRuleCall_3; } //IntersectionTypeExpressionOLD public RuleCall getIntersectionTypeExpressionOLDParserRuleCall_4() { return cIntersectionTypeExpressionOLDParserRuleCall_4; } } |
data class | Data Class | t | f | t | 0 | 11614 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ts/src-gen/org/eclipse/n4js/ts/services/TypeExpressionsGrammarAccess.java/#L201-L255 | 1 | 1662 | 11614 | minor | ||
| 1250 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-config-propertyType", propOrder = { "descriptions", "displayNames", "icon", "propertyName", "propertyClass", "defaultValue", "suggestedValue", "propertyExtension" }) public class FacesProperty { @XmlTransient protected TextMap description = new TextMap(); @XmlTransient protected TextMap displayName = new TextMap(); @XmlElement(name = "icon", required = true) protected LocalCollection icon = new LocalCollection(); @XmlElement(name = "property-name", required = true) protected java.lang.String propertyName; @XmlElement(name = "property-class", required = true) protected java.lang.String propertyClass; @XmlElement(name = "default-value") protected java.lang.String defaultValue; @XmlElement(name = "suggested-value") protected java.lang.String suggestedValue; @XmlElement(name = "property-extension") protected List propertyExtension; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlElement(name = "description", required = true) public Text[] getDescriptions() { return description.toArray(); } public void setDescriptions(Text[] text) { description.set(text); } public String getDescription() { return description.get(); } @XmlElement(name = "display-name", required = true) public Text[] getDisplayNames() { return displayName.toArray(); } public void setDisplayNames(Text[] text) { displayName.set(text); } public String getDisplayName() { return displayName.get(); } public Collection getIcons() { if (icon == null) { icon = new LocalCollection(); } return icon; } public Map getIconMap() { if (icon == null) { icon = new LocalCollection(); } return icon.toMap(); } public Icon getIcon() { return icon.getLocal(); } /** * Gets the value of the propertyName property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyName() { return propertyName; } /** * Sets the value of the propertyName property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyName(java.lang.String value) { this.propertyName = value; } /** * Gets the value of the propertyClass property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getPropertyClass() { return propertyClass; } /** * Sets the value of the propertyClass property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setPropertyClass(java.lang.String value) { this.propertyClass = value; } /** * Gets the value of the defaultValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getDefaultValue() { return defaultValue; } /** * Sets the value of the defaultValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setDefaultValue(java.lang.String value) { this.defaultValue = value; } /** * Gets the value of the suggestedValue property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Sets the value of the suggestedValue property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setSuggestedValue(java.lang.String value) { this.suggestedValue = value; } /** * Gets the value of the propertyExtension property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the propertyExtension property. * * * For example, to add a new item, do as follows: * * getPropertyExtension().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link FacesPropertyExtension } * * */ public List getPropertyExtension() { if (propertyExtension == null) { propertyExtension = new ArrayList(); } return this.propertyExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } } |
data class | blob, data class | t | t | t | blob | 0 | 10436 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/FacesProperty.java/#L70-L298 | 1 | 1250 | 10436 | critical | |
| 5639 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10918 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5639 | 10918 | minor | ||
| 1810 | YES, I found bad smells, the bad smells are: 1. Long method 2. Repetitive code for removing double underscores 3. Excessive use of nested loops 4. Feature envy (the method is performing operations that should be done by another object) 5. Magic numbers without explanatory comments 6. Poor naming conventions (i, usIndex) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long method2 Repetitive code for removing double underscores3 Excessive use of nested loops4 Feature envy (the method is performing operations that should be done by another object)5 Magic numbers without explanatory comments6 Poor naming conventions (i, usIndex) | t | f | t | usIndex) | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 2 | 1810 | 12056 | major | |
| 346 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3525 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 346 | 3525 | minor | |
| 904 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy3 Duplicate code | t | f | t | 0 | 8176 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 904 | 8176 | minor | ||
| 1677 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11648 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 1677 | 11648 | minor | ||
| 1818 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 12089 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 1818 | 12089 | minor | |
| 2078 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | long method | t | t | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 1 | 2078 | 13053 | minor | ||
| 1030 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method | t | t | t | 0 | 9383 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1030 | 9383 | major | ||
| 3862 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShapeMarshaller { private String action; private String verb; private String target; private String requestUri; private String locationName; private String xmlNameSpaceUri; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public ShapeMarshaller withAction(String action) { setAction(action); return this; } public String getVerb() { return verb; } public void setVerb(String verb) { this.verb = verb; } public ShapeMarshaller withVerb(String verb) { setVerb(verb); return this; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public ShapeMarshaller withTarget(String target) { setTarget(target); return this; } public String getRequestUri() { return requestUri; } public void setRequestUri(String requestUri) { this.requestUri = requestUri; } public ShapeMarshaller withRequestUri(String requestUri) { setRequestUri(requestUri); return this; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public ShapeMarshaller withLocationName(String locationName) { setLocationName(locationName); return this; } public String getXmlNameSpaceUri() { return xmlNameSpaceUri; } public void setXmlNameSpaceUri(String xmlNameSpaceUri) { this.xmlNameSpaceUri = xmlNameSpaceUri; } public ShapeMarshaller withXmlNameSpaceUri(String xmlNameSpaceUri) { setXmlNameSpaceUri(xmlNameSpaceUri); return this; } } |
data class | data class | t | t | t | 0 | 10055 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/ShapeMarshaller.java/#L18-L109 | 1 | 3862 | 10055 | critical | ||
| 635 | YES I found bad smells the bad smells are: Long method, Feature envy, long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean configureHA(final Long resourceId, final HAResource.ResourceType resourceType, final Boolean enable, final String haProvider) { return Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { HAConfigVO haConfig = (HAConfigVO) haConfigDao.findHAResource(resourceId, resourceType); if (haConfig == null) { haConfig = new HAConfigVO(); if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (enable != null) { haConfig.setEnabled(enable); haConfig.setManagementServerId(ManagementServerNode.getManagementServerId()); } haConfig.setResourceId(resourceId); haConfig.setResourceType(resourceType); if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } if (haConfigDao.persist(haConfig) != null) { return true; } } else { if (enable != null) { haConfig.setEnabled(enable); } if (haProvider != null) { haConfig.setHaProvider(haProvider); } if (Strings.isNullOrEmpty(haConfig.getHaProvider())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "HAProvider is not provided for the resource, failing configuration."); } return haConfigDao.update(haConfig.getId(), haConfig); } return false; } }); } |
long method | Long method, Feature envy, long parameter list | t | f | t | Feature envy, long parameter list | 0 | 6305 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/org/apache/cloudstack/ha/HAManagerImpl.java/#L337-L374 | 2 | 635 | 6305 | major | |
| 1790 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void paintComponent(Graphics g) { XPStyle xp = XPStyle.getXP(); paintTitleBackground(g); String title = frame.getTitle(); if (title != null) { boolean isSelected = frame.isSelected(); Font oldFont = g.getFont(); Font newFont = (titleFont != null) ? titleFont : getFont(); g.setFont(newFont); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, newFont); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) { lastIconBounds = iconButton.getBounds(); } else if (frame.isMaximizable()) { lastIconBounds = maxButton.getBounds(); } else if (frame.isClosable()) { lastIconBounds = closeButton.getBounds(); } int titleX; int titleW; int gap = 2; if (WindowsGraphicsUtils.isLeftToRight(frame)) { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getWidth() - frame.getInsets().right; } titleX = systemLabel.getX() + systemLabel.getWidth() + gap; if (xp != null) { titleX += 2; } titleW = lastIconBounds.x - titleX - gap; } else { if (lastIconBounds.x == 0) { // There are no icons lastIconBounds.x = frame.getInsets().left; } titleW = SwingUtilities2.stringWidth(frame, fm, title); int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; if (xp != null) { minTitleX += 2; } int availableWidth = systemLabel.getX() - gap - minTitleX; if (availableWidth > titleW) { titleX = systemLabel.getX() - gap - titleW; } else { titleX = minTitleX; titleW = availableWidth; } } title = getTitle(frame.getTitle(), fm, titleW); if (xp != null) { String shadowType = null; if (isSelected) { shadowType = xp.getString(this, Part.WP_CAPTION, State.ACTIVE, Prop.TEXTSHADOWTYPE); } if ("single".equalsIgnoreCase(shadowType)) { Point shadowOffset = xp.getPoint(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWOFFSET); Color shadowColor = xp.getColor(this, Part.WP_WINDOW, State.ACTIVE, Prop.TEXTSHADOWCOLOR, null); if (shadowOffset != null && shadowColor != null) { g.setColor(shadowColor); SwingUtilities2.drawString(frame, g, title, titleX + shadowOffset.x, baseline + shadowOffset.y); } } } g.setColor(isSelected ? selectedTextColor : notSelectedTextColor); SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(oldFont); } } |
long method | Long method2 Duplicate code | t | f | t | 0 | 11987 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/windows/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java/#L125-L205 | 2 | 1790 | 11987 | minor | ||
| 603 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DCSerialField extends DCBlockTag implements SerialFieldTree { public final DCIdentifier name; public final DCReference type; public final List description; DCSerialField(DCIdentifier name, DCReference type, List description) { this.description = description; this.name = name; this.type = type; } @Override @DefinedBy(Api.COMPILER_TREE) public Kind getKind() { return Kind.SERIAL_FIELD; } @Override @DefinedBy(Api.COMPILER_TREE) public R accept(DocTreeVisitor v, D d) { return v.visitSerialField(this, d); } @Override @DefinedBy(Api.COMPILER_TREE) public List getDescription() { return description; } @Override @DefinedBy(Api.COMPILER_TREE) public IdentifierTree getName() { return name; } @Override @DefinedBy(Api.COMPILER_TREE) public ReferenceTree getType() { return type; } } |
data class | data class | t | t | t | 0 | 6013 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DCTree.java/#L732-L767 | 1 | 603 | 6013 | major | ||
| 2191 | { "output": "YES I found bad smells", "detectedBadSmells": [ { "bad smells are": [ "Data Class", "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | bad smells are: data class, long method | t | t | t | long method | 0 | 13466 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 2191 | 13466 | minor | |
| 206 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TruffleNFI_DLL implements DLLRFFI { public static final class NFIHandle implements LibHandle { @SuppressWarnings("unused") private final String libName; final TruffleObject libHandle; NFIHandle(String libName, TruffleObject libHandle) { this.libName = libName; this.libHandle = libHandle; } @Override public Type getRFFIType() { return RFFIFactory.Type.NFI; } } private static final class TruffleNFI_DLOpenNode extends Node implements DLLRFFI.DLOpenNode { @Override @TruffleBoundary public LibHandle execute(String path, boolean local, boolean now) { String librffiPath = LibPaths.getBuiltinLibPath("R"); // Do not call before/afterDowncall when loading libR to prevent the pushing/popping of // the callback array, which requires that the libR have already been loaded boolean notifyStateRFFI = !librffiPath.equals(path); long before = notifyStateRFFI ? RContext.getInstance().getStateRFFI().beforeDowncall(RFFIFactory.Type.NFI) : 0; try { String libName = DLL.libName(path); Env env = RContext.getInstance().getEnv(); TruffleObject libHandle = (TruffleObject) env.parse(Source.newBuilder("nfi", prepareLibraryOpen(path, local, now), path).build()).call(); return new NFIHandle(libName, libHandle); } finally { if (notifyStateRFFI) { RContext.getInstance().getStateRFFI().afterDowncall(before, RFFIFactory.Type.NFI); } } } } @TruffleBoundary private static String prepareLibraryOpen(String path, boolean local, boolean now) { StringBuilder sb = new StringBuilder("load"); sb.append("("); sb.append(local ? "RTLD_LOCAL" : "RTLD_GLOBAL"); sb.append('|'); sb.append(now ? "RTLD_NOW" : "RTLD_LAZY"); sb.append(") \""); sb.append(path); sb.append('"'); return sb.toString(); } private static class TruffleNFI_DLSymNode extends Node implements DLLRFFI.DLSymNode { @Child private Node lookupSymbol; @Override @TruffleBoundary public SymbolHandle execute(Object handle, String symbol) { assert handle instanceof NFIHandle; NFIHandle nfiHandle = (NFIHandle) handle; if (lookupSymbol == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); lookupSymbol = insert(Message.READ.createNode()); } try { TruffleObject result = (TruffleObject) ForeignAccess.sendRead(lookupSymbol, nfiHandle.libHandle, symbol); return new SymbolHandle(result); } catch (UnknownIdentifierException e) { throw new UnsatisfiedLinkError(); } catch (InteropException e) { throw RInternalError.shouldNotReachHere(); } } } private static class TruffleNFI_DLCloseNode extends Node implements DLLRFFI.DLCloseNode { @Override public int execute(Object handle) { assert handle instanceof NFIHandle; // TODO return 0; } } @Override public DLOpenNode createDLOpenNode() { return new TruffleNFI_DLOpenNode(); } @Override public DLSymNode createDLSymNode() { return new TruffleNFI_DLSymNode(); } @Override public DLCloseNode createDLCloseNode() { return new TruffleNFI_DLCloseNode(); } } |
blob | blob, long method | t | t | t | long method | 0 | 2304 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.ffi.impl/src/com/oracle/truffle/r/ffi/impl/nfi/TruffleNFI_DLL.java/#L44-L145 | 1 | 206 | 2304 | minor | |
| 2577 | { "response": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Unstable public class JobStatusChangedEvent implements HistoryEvent { private JobStatusChanged datum = new JobStatusChanged(); /** * Create an event to record the change in the Job Status * @param id Job ID * @param jobStatus The new job status */ public JobStatusChangedEvent(JobID id, String jobStatus) { datum.jobid = new Utf8(id.toString()); datum.jobStatus = new Utf8(jobStatus); } JobStatusChangedEvent() {} public Object getDatum() { return datum; } public void setDatum(Object datum) { this.datum = (JobStatusChanged)datum; } /** Get the Job Id */ public JobID getJobId() { return JobID.forName(datum.jobid.toString()); } /** Get the event status */ public String getStatus() { return datum.jobStatus.toString(); } /** Get the event type */ public EventType getEventType() { return EventType.JOB_STATUS_CHANGED; } } |
data class | 1: data class | t | t | t | 0 | 14935 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/java/org/apache/hadoop/mapreduce/jobhistory/JobStatusChangedEvent.java/#L33-L64 | 1 | 2577 | 14935 | minor | ||
| 1045 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9454 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1045 | 9454 | major | ||
| 4676 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ServiceDefinition[] findServicesByToolID(final String toolId) { try { ensureDiskCacheLoaded(); accessLock.readLock().lock(); final boolean returnAll = toolId == null || toolId.length() == 0; final List requestedDefinitions = new ArrayList(); // Iterate the map of service types. Values are a map of service // instances. for (final Map mapServiceInstances : mapServices.values()) { for (final ServiceDefinition definition : mapServiceInstances.values()) { /* * NB! some service definitions in Dev12 QU1 may have null * ToolID */ if (returnAll || toolId.equalsIgnoreCase(definition.getToolID())) { requestedDefinitions.add((ServiceDefinition) definition.clone()); } } } // Return null if no matching definitions were found. if (requestedDefinitions.size() == 0) { return null; } // Return an array of the matching service definitions. return requestedDefinitions.toArray(new ServiceDefinition[requestedDefinitions.size()]); } finally { accessLock.readLock().unlock(); } } |
long method | long method, data class | t | t | t | data class | 0 | 12504 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/framework/location/internal/LocationCacheManager.java/#L399-L431 | 1 | 4676 | 12504 | minor | |
| 2224 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class ResourceMethodConfigImpl implements ResourceMethodConfig { private final ConfigValue _timeoutMs; ResourceMethodConfigImpl(ConfigValue timeoutMs) { _timeoutMs = timeoutMs; } public ConfigValue getTimeoutMs() { return _timeoutMs; } @Override public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceMethodConfigImpl that = (ResourceMethodConfigImpl) o; return Objects.equals(_timeoutMs, that._timeoutMs); } @Override public int hashCode() { return Objects.hash(_timeoutMs); } } |
data class | data class | t | t | t | 0 | 13570 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/config/ResourceMethodConfigImpl.java/#L13-L49 | 1 | 2224 | 13570 | major | ||
| 692 | YES I found bad smells, the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Complex conditional logic 6. Inappropriate commenting 7. Missing error handling 8. Inconsistent formatting 9. Inconsistent variable naming conventions 10. Inefficient use of string concatenation in a loop 11. Hard-coded paths and file names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
feature envy | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Complex conditional logic6 Inappropriate commenting7 Missing error handling8 Inconsistent formatting9 Inconsistent variable naming conventions | t | f | t | 0 | 6653 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 692 | 6653 | minor | ||
| 2539 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static JsonWebKey fromRSAPrivateKey(RSAPrivateKey pk, String algo, String kid) { JsonWebKey jwk = prepareRSAJwk(pk.getModulus(), algo, kid); String encodedPrivateExponent = Base64UrlUtility.encode(pk.getPrivateExponent().toByteArray()); jwk.setProperty(JsonWebKey.RSA_PRIVATE_EXP, encodedPrivateExponent); if (pk instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey pkCrt = (RSAPrivateCrtKey)pk; jwk.setProperty(JsonWebKey.RSA_PUBLIC_EXP, Base64UrlUtility.encode(pkCrt.getPublicExponent().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR, Base64UrlUtility.encode(pkCrt.getPrimeQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentP().toByteArray())); jwk.setProperty(JsonWebKey.RSA_SECOND_PRIME_CRT, Base64UrlUtility.encode(pkCrt.getPrimeExponentQ().toByteArray())); jwk.setProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT, Base64UrlUtility.encode(pkCrt.getCrtCoefficient().toByteArray())); } // "oth" can be populated too if needed return jwk; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14771 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/rt/rs/security/jose-parent/jose/src/main/java/org/apache/cxf/rs/security/jose/jwk/JwkUtils.java/#L448-L469 | 2 | 2539 | 14771 | major | |
| 230 | { "response": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 1 | 230 | 2513 | minor | |
| 3986 | Please start your answer with"YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". YES I found bad smells: 1. Long method, 2. Repeated code, 3. Catch-all exception, 4. Unclear/inefficient variable names, 5. Possible feature envy with the repeated calls to oDataJPAContext.getODataJPATransaction(), 6. Possible violation of Single Responsibility Principle with the multiple functions being performed by the method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | Long method, 2 Repeated code, 3 Catch-all exception, 4 Unclear/inefficient variable names, 5 Possible feature envy with the repeated calls to oDataJPAContextgetODataJPATransaction(), 6 Possible violation of Single Responsibility Principle with the multiple functions being performed by the method | t | f | t | . Long method, 2. Repeated code, 3. Catch-all exception, 4. Unclear/inefficient variable names, 6. Possible violation of Single Responsibility Principle with the multiple functions being performed by the method. | 0 | 10501 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 3986 | 10501 | minor | |
| 1678 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11649 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 1678 | 11649 | major | ||
| 1147 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10122 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 1147 | 10122 | major | ||
| 1543 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 2 | 1543 | 11243 | critical | ||
| 963 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private LdapComparator classLoadComparator( SchemaManager schemaManager, String oid, String className, Attribute byteCode ) throws LdapException { // Try to class load the comparator LdapComparator comparator; Class clazz; String byteCodeStr = StringConstants.EMPTY; if ( byteCode == null ) { try { clazz = Class.forName( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) ); } } else { classLoader.setAttribute( byteCode ); try { clazz = classLoader.loadClass( className ); } catch ( ClassNotFoundException cnfe ) { LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) ); } byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) ); } // Create the comparator instance. Either we have a no argument constructor, // or we have one which takes an OID. Lets try the one with an OID argument first try { Constructor constructor = clazz.getConstructor( new Class[] { String.class } ); try { comparator = ( LdapComparator ) constructor.newInstance( oid ); } catch ( InvocationTargetException ite ) { LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) ); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException ie ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) ); } } catch ( NoSuchMethodException nsme ) { // Ok, let's try with the constructor without argument. // In this case, we will have to check that the OID is the same than // the one we got in the Comparator entry try { clazz.getConstructor(); } catch ( NoSuchMethodException nsme2 ) { LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) ); } try { comparator = ( LdapComparator ) clazz.newInstance(); } catch ( InstantiationException ie ) { LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) ); } catch ( IllegalAccessException iae ) { LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) ); throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) ); } if ( !comparator.getOid().equals( oid ) ) { String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() ); throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme ); } } // Update the loadable fields comparator.setBytecode( byteCodeStr ); comparator.setFqcn( className ); // Inject the SchemaManager for the comparator who needs it comparator.setSchemaManager( schemaManager ); return comparator; } |
long method | long method, data class | t | t | t | data class | 0 | 8574 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/schema/data/src/main/java/org/apache/directory/api/ldap/schema/loader/SchemaEntityFactory.java/#L514-L623 | 1 | 963 | 8574 | major | |
| 958 | { "message": "YES I found bad smells", "detected_bad_smells": [ "The bad smells are: Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
long method | the bad smells are: long method | t | t | t | 0 | 8556 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 958 | 8556 | minor | ||
| 5507 | {"message": "YES I found bad smells", "bad smells are": ["Long method", "Feature envy"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3711 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5507 | 3711 | critical | |
| 514 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | data class | t | t | t | 0 | 5287 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 1 | 514 | 5287 | major | ||
| 561 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 5662 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 561 | 5662 | minor | |
| 1225 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10351 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 1225 | 10351 | minor | |
| 2369 | YES, I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 14303 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 2369 | 14303 | major | |
| 671 | YES I found bad smells the bad smells are: 1. Long Method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method2 Feature Envy | t | f | t | 0 | 6554 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 671 | 6554 | major | ||
| 4135 | { "response": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultResourceService implements ResourceService { private String servletPath = ""; /** * @param servletPath the servletPath to set */ public void setServletPath(String servletPath) { this.servletPath = servletPath; } public String getServletPath() { return servletPath; } } |
data class | 1. data class | t | t | t | 0 | 10881 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/resources/DefaultResourceService.java/#L23-L38 | 1 | 4135 | 10881 | major | ||
| 136 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, FetchRuleKeyLogsRequest struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RULE_KEYS if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list184 = iprot.readListBegin(); struct.ruleKeys = new java.util.ArrayList(_list184.size); java.lang.String _elem185; for (int _i186 = 0; _i186 < _list184.size; ++_i186) { _elem185 = iprot.readString(); struct.ruleKeys.add(_elem185); } iprot.readListEnd(); } struct.setRuleKeysIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // REPOSITORY if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.repository = iprot.readString(); struct.setRepositoryIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // SCHEDULE_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.scheduleType = iprot.readString(); struct.setScheduleTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // DISTRIBUTED_BUILD_MODE_ENABLED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.distributedBuildModeEnabled = iprot.readBool(); struct.setDistributedBuildModeEnabledIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } |
long method | long method | t | t | t | 0 | 1673 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/distributed/thrift/FetchRuleKeyLogsRequest.java/#L547-L608 | 1 | 136 | 1673 | major | ||
| 2641 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Comments, 4. Magic numbers, 5. Nested if statements, 6. Code duplication, 7. Catching general exceptions, 8. Inconsistent formatting, 9. Inefficient use of conditionals, 10. Unnecessary boolean checks, 11. Lack of abstraction, 12. Inappropriate error handling, 13. Inappropriate logging levels, 14. Poor naming conventions, 15. Inconsistent use of exception types. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method, 2 Feature envy, 3 Comments, 4 Magic numbers, 5 Nested if statements, 6 Code duplication, 7 Catching general exceptions, 8 Inconsistent formatting, 9 Inefficient use of conditionals, | t | f | t | . Long method, 3. Comments, 4. Magic numbers, 5. Nested if statements, 6. Code duplication, 7. Catching general exceptions, 8. Inconsistent formatting, 9. Inefficient use of conditionals, | 0 | 15144 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2641 | 15144 | minor | |
| 473 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | 1. data class | t | t | f | data class | 0 | 4576 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 473 | 4576 | minor | |
| 722 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Message chain 4. Duplicated code 5. Primitive obsession 6. Lazy class 7. Shotgun surgery | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | Long method2 Feature envy3 Message chain4 Duplicated code 5 Primitive obsession6 Lazy class7 Shotgun surgery | t | f | t | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 722 | 6833 | minor | ||
| 1555 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long Method | t | f | t | 0 | 11276 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 1 | 1555 | 11276 | minor | ||
| 1043 | YES I found bad smells the bad smells are: Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void start(Stage stage) { try { // create splitPane pane and JavaFX app scene SplitPane splitPane = new SplitPane(); splitPane.setOrientation(Orientation.VERTICAL); Scene fxScene = new Scene(splitPane); // set title, size, and add JavaFX scene to stage stage.setTitle("Feature Layer Rendering Mode Map Sample"); stage.setWidth(800); stage.setHeight(700); stage.setScene(fxScene); stage.show(); // create a map (top) and set it to render all features in static rendering mode ArcGISMap mapTop = new ArcGISMap(); mapTop.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); mapTop.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.STATIC); // create a map (bottom) and set it to render all features in dynamic rendering mode ArcGISMap mapBottom = new ArcGISMap(); mapBottom.getLoadSettings().setPreferredPointFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolylineFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); mapBottom.getLoadSettings().setPreferredPolygonFeatureRenderingMode(FeatureLayer.RenderingMode.DYNAMIC); // creating top map view mapViewTop = new MapView(); mapViewTop.setMap(mapTop); splitPane.getItems().add(mapViewTop); // creating bottom map view mapViewBottom = new MapView(); mapViewBottom.setMap(mapBottom); splitPane.getItems().add(mapViewBottom); // create service feature table using a point, polyline, and polygon service ServiceFeatureTable pointServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0"); ServiceFeatureTable polylineServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8"); ServiceFeatureTable polygonServiceFeatureTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9"); // create feature layer from service feature tables FeatureLayer pointFeatureLayer = new FeatureLayer(pointServiceFeatureTable); FeatureLayer polylineFeatureLayer = new FeatureLayer(polylineServiceFeatureTable); FeatureLayer polygonFeatureLayer = new FeatureLayer(polygonServiceFeatureTable); // add each layer to top and bottom map mapTop.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer, polylineFeatureLayer, polygonFeatureLayer)); mapBottom.getOperationalLayers().addAll(Arrays.asList(pointFeatureLayer.copy(), polylineFeatureLayer.copy(), polygonFeatureLayer.copy())); // viewpoint locations for map view to zoom in and out to Viewpoint zoomOutPoint = new Viewpoint(new Point(-118.37, 34.46, SpatialReferences.getWgs84()), 650000, 0); Viewpoint zoomInPoint = new Viewpoint(new Point(-118.45, 34.395, SpatialReferences.getWgs84()), 50000, 90); mapViewTop.setViewpoint(zoomOutPoint); mapViewBottom.setViewpoint(zoomOutPoint); //loop an animation into and out from the zoom in point (5 seconds each) with a 2 second gap between zooming timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(7), event -> zoomTo(zoomInPoint))); timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(14), event -> zoomTo(zoomOutPoint))); timeline.play(); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } |
long method | Long method, Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | t | f | t | Repetitive code, Magic numbers, Nested loop/conditionals, Duplicate code, Data clumps, Long parameter list | 0 | 9446 | https://github.com/Esri/arcgis-runtime-samples-java/blob/c7a0b309586495ff9cc9dbed129e411943547793/src/main/java/com/esri/samples/featurelayers/feature_layer_rendering_mode_map/FeatureLayerRenderingModeMapSample.java/#L45-L114 | 2 | 1043 | 9446 | major | |
| 2500 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Error handling mixed with business logic, 5. Excessive comments, 6. Poor exception handling, 7. Code style inconsistencies, 8. Magic numbers, 9. Inefficient use of data structures (e.g. using HashMap instead of List), 10. Poor naming conventions for variables and methods, 11. Complexity and unreadability, 12. Too many nested conditions, 13. Excessive use of context.getProperty(), 14. Poor separation of concerns, 15. Excessive use of session (e.g. session.transfer()), 16. Long parameter list, 17. Lack of encapsulation, 18. Code smells in for loop, 19. Excessive log statements, 20. Not using best practices (e.g. using StringUtils.isBlank instead of StringUtils.isEmpty). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Error handling mixed with business logic, 5 Excessive comments, 6 Poor exception handling, 7 Code style inconsistencies, 8 Magic numbers, 9 Inefficient use of data structures (eg using HashMap instead of List), | t | f | t | . Long method, 3. Duplicate code, 4. Error handling mixed with business logic, 5. Excessive comments, 6. Poor exception handling, 7. Code style inconsistencies, 8. Magic numbers, 9. Inefficient use of data structures (e.g. using HashMap instead of List), | 0 | 14653 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2500 | 14653 | major | |
| 1882 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12288 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 1882 | 12288 | minor | ||
| 592 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | blob, long method | t | t | t | blob | 0 | 5902 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 592 | 5902 | minor | |
| 2486 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 14610 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 2486 | 14610 | minor | ||
| 2048 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Use of nested maps and loops, which can make the code difficult to read and maintain 4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component 5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality. 6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java. 7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | Long method2 Feature envy3 Use of nested maps and loops, which can make the code difficult to read and maintain4 Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5 Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality6 Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java7 Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers | t | f | t | which can make the code difficult to read and maintain4. Lack of proper naming conventions for variables and methods, making it difficult to understand the purpose of each component5. Lack of comments and documentation, making it difficult for other developers to understand the code's purpose and functionality.6. Unnecessary use of try-finally block, which could be replaced with a try-with-resources block in newer versions of Java.7. Overuse of lambdas and functional programming style, which can make the code difficult to read and maintain for some developers. | 0 | 12878 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 2 | 2048 | 12878 | major | |
| 1745 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number (n > 0, index < n-1, index > 0) 3. Feature envy (container.getLength(), container.indexOf()) 4. Duplicated code (similar code blocks for FORWARD and BACKWARD cases) 5. Switch statement without a default case 6. Poor exception handling (throwing IllegalArgumentException instead of specific exceptions, ignoring other possible exceptions) 7. Lack of comments/documentation to explain the purpose of the method and its parameters/return value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | Long method 2 Magic number (n > 0, index < n- | t | f | t | index < n- | 0 | 11851 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 2 | 1745 | 11851 | major | |
| 674 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 674 | 6568 | minor | |
| 3940 | YES I found bad smells the bad smells are: 1. Long Method 2. Duplicate Code 3. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | Long Method2 Duplicate Code3 Feature Envy | t | f | t | 0 | 10313 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 2 | 3940 | 10313 | major | ||
| 5709 | { "message": "YES I found bad smells", "the bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12658 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5709 | 12658 | critical | |
| 2523 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | long method, data class | t | t | t | data class | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 1 | 2523 | 14713 | minor | |
| 2003 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 1 | 2003 | 12716 | critical | |
| 1985 | {"message": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | 1. long method | t | t | t | 0 | 12651 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 1 | 1985 | 12651 | major | ||
| 1105 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Private final class NflyFSystem extends FileSystem { private static final Log LOG = LogFactory.getLog(NflyFSystem.class); private static final String NFLY_TMP_PREFIX = "_nfly_tmp_"; enum NflyKey { // minimum replication, if local filesystem is included +1 is recommended minReplication, // forces to check all the replicas and fetch the one with the most recent // time stamp // readMostRecent, // create missing replica from far to near, including local? repairOnRead } private static final int DEFAULT_MIN_REPLICATION = 2; private static URI nflyURI = URI.create("nfly:///"); private final NflyNode[] nodes; private final int minReplication; private final EnumSet nflyFlags; private final Node myNode; private final NetworkTopology topology; /** * URI's authority is used as an approximation of the distance from the * client. It's sufficient for DC but not accurate because worker nodes can be * closer. */ private static class NflyNode extends NodeBase { private final ChRootedFileSystem fs; NflyNode(String hostName, String rackName, URI uri, Configuration conf) throws IOException { this(hostName, rackName, new ChRootedFileSystem(uri, conf)); } NflyNode(String hostName, String rackName, ChRootedFileSystem fs) { super(hostName, rackName); this.fs = fs; } ChRootedFileSystem getFs() { return fs; } @Override public boolean equals(Object o) { // satisfy findbugs return super.equals(o); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } } private static final class MRNflyNode extends NflyNode implements Comparable { private FileStatus status; private MRNflyNode(NflyNode n) { super(n.getName(), n.getNetworkLocation(), n.fs); } private void updateFileStatus(Path f) throws IOException { final FileStatus tmpStatus = getFs().getFileStatus(f); status = tmpStatus == null ? notFoundStatus(f) : tmpStatus; } // TODO allow configurable error margin for FileSystems with different // timestamp precisions @Override public int compareTo(MRNflyNode other) { if (status == null) { return other.status == null ? 0 : 1; // move non-null towards head } else if (other.status == null) { return -1; // move this towards head } else { final long mtime = status.getModificationTime(); final long their = other.status.getModificationTime(); return Long.compare(their, mtime); // move more recent towards head } } @Override public boolean equals(Object o) { if (!(o instanceof MRNflyNode)) { return false; } MRNflyNode other = (MRNflyNode) o; return 0 == compareTo(other); } @Override public int hashCode() { // satisfy findbugs return super.hashCode(); } private FileStatus nflyStatus() throws IOException { return new NflyStatus(getFs(), status); } private FileStatus cloneStatus() throws IOException { return new FileStatus(status.getLen(), status.isDirectory(), status.getReplication(), status.getBlockSize(), status.getModificationTime(), status.getAccessTime(), null, null, null, status.isSymlink() ? status.getSymlink() : null, status.getPath()); } } private MRNflyNode[] workSet() { final MRNflyNode[] res = new MRNflyNode[nodes.length]; for (int i = 0; i < res.length; i++) { res[i] = new MRNflyNode(nodes[i]); } return res; } /** * Utility to replace null with DEFAULT_RACK. * * @param rackString rack value, can be null * @return non-null rack string */ private static String getRack(String rackString) { return rackString == null ? NetworkTopology.DEFAULT_RACK : rackString; } /** * Creates a new Nfly instance. * * @param uris the list of uris in the mount point * @param conf configuration object * @param minReplication minimum copies to commit a write op * @param nflyFlags modes such readMostRecent * @throws IOException */ private NflyFSystem(URI[] uris, Configuration conf, int minReplication, EnumSet nflyFlags) throws IOException { if (uris.length < minReplication) { throw new IOException(minReplication + " < " + uris.length + ": Minimum replication < #destinations"); } setConf(conf); final String localHostName = InetAddress.getLocalHost().getHostName(); // build a list for topology resolution final List hostStrings = new ArrayList(uris.length + 1); for (URI uri : uris) { final String uriHost = uri.getHost(); // assume local file system or another closest filesystem if no authority hostStrings.add(uriHost == null ? localHostName : uriHost); } // resolve the client node hostStrings.add(localHostName); final DNSToSwitchMapping tmpDns = ReflectionUtils.newInstance(conf.getClass( CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); // this is an ArrayList final List rackStrings = tmpDns.resolve(hostStrings); nodes = new NflyNode[uris.length]; final Iterator rackIter = rackStrings.iterator(); for (int i = 0; i < nodes.length; i++) { nodes[i] = new NflyNode(hostStrings.get(i), rackIter.next(), uris[i], conf); } // sort all the uri's by distance from myNode, the local file system will // automatically be the the first one. // myNode = new NodeBase(localHostName, getRack(rackIter.next())); topology = NetworkTopology.getInstance(conf); topology.sortByDistance(myNode, nodes, nodes.length); this.minReplication = minReplication; this.nflyFlags = nflyFlags; statistics = getStatistics(nflyURI.getScheme(), getClass()); } /** * Transactional output stream. When creating path /dir/file * 1) create invisible /real/dir_i/_nfly_tmp_file * 2) when more than min replication was written, write is committed by * renaming all successfully written files to /real/dir_i/file */ private final class NflyOutputStream extends OutputStream { // actual path private final Path nflyPath; // tmp path before commit private final Path tmpPath; // broadcast set private final FSDataOutputStream[] outputStreams; // status set: 1 working, 0 problem private final BitSet opSet; private final boolean useOverwrite; private NflyOutputStream(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { nflyPath = f; tmpPath = getNflyTmpPath(f); outputStreams = new FSDataOutputStream[nodes.length]; for (int i = 0; i < outputStreams.length; i++) { outputStreams[i] = nodes[i].fs.create(tmpPath, permission, true, bufferSize, replication, blockSize, progress); } opSet = new BitSet(outputStreams.length); opSet.set(0, outputStreams.length); useOverwrite = false; } // // TODO consider how to clean up and throw an exception early when the clear // bits under min replication // private void mayThrow(List ioExceptions) throws IOException { final IOException ioe = MultipleIOException .createIOException(ioExceptions); if (opSet.cardinality() < minReplication) { throw ioe; } else { if (LOG.isDebugEnabled()) { LOG.debug("Exceptions occurred: " + ioe); } } } @Override public void write(int d) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >=0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(d); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } private void osException(int i, String op, Throwable t, List ioExceptions) { opSet.clear(i); processThrowable(nodes[i], op, t, ioExceptions, tmpPath, nflyPath); } @Override public void write(byte[] bytes, int offset, int len) throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].write(bytes, offset, len); } catch (Throwable t) { osException(i, "write", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void flush() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].flush(); } catch (Throwable t) { osException(i, "flush", t, ioExceptions); } } mayThrow(ioExceptions); } @Override public void close() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { outputStreams[i].close(); } catch (Throwable t) { osException(i, "close", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { cleanupAllTmpFiles(); throw new IOException("Failed to sufficiently replicate: min=" + minReplication + " actual=" + opSet.cardinality()); } else { commit(); } } private void cleanupAllTmpFiles() throws IOException { for (int i = 0; i < outputStreams.length; i++) { try { nodes[i].fs.delete(tmpPath); } catch (Throwable t) { processThrowable(nodes[i], "delete", t, null, tmpPath); } } } private void commit() throws IOException { final List ioExceptions = new ArrayList(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { final NflyNode nflyNode = nodes[i]; try { if (useOverwrite) { nflyNode.fs.delete(nflyPath); } nflyNode.fs.rename(tmpPath, nflyPath); } catch (Throwable t) { osException(i, "commit", t, ioExceptions); } } if (opSet.cardinality() < minReplication) { // cleanup should be done outside. If rename failed, it's unlikely that // delete will work either. It's the same kind of metadata-only op // throw MultipleIOException.createIOException(ioExceptions); } // best effort to have a consistent timestamp final long commitTime = System.currentTimeMillis(); for (int i = opSet.nextSetBit(0); i >= 0; i = opSet.nextSetBit(i + 1)) { try { nodes[i].fs.setTimes(nflyPath, commitTime, commitTime); } catch (Throwable t) { LOG.info("Failed to set timestamp: " + nodes[i] + " " + nflyPath); } } } } private Path getNflyTmpPath(Path f) { return new Path(f.getParent(), NFLY_TMP_PREFIX + f.getName()); } /** * // TODO * Some file status implementations have expensive deserialization or metadata * retrieval. This probably does not go beyond RawLocalFileSystem. Wrapping * the the real file status to preserve this behavior. Otherwise, calling * realStatus getters in constructor defeats this design. */ static final class NflyStatus extends FileStatus { private static final long serialVersionUID = 0x21f276d8; private final FileStatus realStatus; private final String strippedRoot; private NflyStatus(ChRootedFileSystem realFs, FileStatus realStatus) throws IOException { this.realStatus = realStatus; this.strippedRoot = realFs.stripOutRoot(realStatus.getPath()); } String stripRoot() throws IOException { return strippedRoot; } @Override public long getLen() { return realStatus.getLen(); } @Override public boolean isFile() { return realStatus.isFile(); } @Override public boolean isDirectory() { return realStatus.isDirectory(); } @Override public boolean isSymlink() { return realStatus.isSymlink(); } @Override public long getBlockSize() { return realStatus.getBlockSize(); } @Override public short getReplication() { return realStatus.getReplication(); } @Override public long getModificationTime() { return realStatus.getModificationTime(); } @Override public long getAccessTime() { return realStatus.getAccessTime(); } @Override public FsPermission getPermission() { return realStatus.getPermission(); } @Override public String getOwner() { return realStatus.getOwner(); } @Override public String getGroup() { return realStatus.getGroup(); } @Override public Path getPath() { return realStatus.getPath(); } @Override public void setPath(Path p) { realStatus.setPath(p); } @Override public Path getSymlink() throws IOException { return realStatus.getSymlink(); } @Override public void setSymlink(Path p) { realStatus.setSymlink(p); } @Override public boolean equals(Object o) { return realStatus.equals(o); } @Override public int hashCode() { return realStatus.hashCode(); } @Override public String toString() { return realStatus.toString(); } } @Override public URI getUri() { return nflyURI; } /** * Category: READ. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. * @return input stream according to nfly flags (closest, most recent) * @throws IOException * @throws FileNotFoundException iff all destinations generate this exception */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); // naively iterate until one can be opened // for (final MRNflyNode nflyNode : mrNodes) { try { if (nflyFlags.contains(NflyKey.repairOnRead) || nflyFlags.contains(NflyKey.readMostRecent)) { // calling file status to avoid pulling bytes prematurely nflyNode.updateFileStatus(f); } else { return nflyNode.getFs().open(f, bufferSize); } } catch (FileNotFoundException fnfe) { nflyNode.status = notFoundStatus(f); numNotFounds++; processThrowable(nflyNode, "open", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "open", t, ioExceptions, f); } } if (nflyFlags.contains(NflyKey.readMostRecent)) { // sort from most recent to least recent Arrays.sort(mrNodes); } final FSDataInputStream fsdisAfterRepair = repairAndOpen(mrNodes, f, bufferSize); if (fsdisAfterRepair != null) { return fsdisAfterRepair; } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static FileStatus notFoundStatus(Path f) { return new FileStatus(-1, false, 0, 0, 0, f); } /** * Iterate all available nodes in the proximity order to attempt repair of all * FileNotFound nodes. * * @param mrNodes work set copy of nodes * @param f path to repair and open * @param bufferSize buffer size for read RPC * @return the closest/most recent replica stream AFTER repair */ private FSDataInputStream repairAndOpen(MRNflyNode[] mrNodes, Path f, int bufferSize) { long maxMtime = 0L; for (final MRNflyNode srcNode : mrNodes) { if (srcNode.status == null // not available || srcNode.status.getLen() < 0L) { // not found continue; // not available } if (srcNode.status.getModificationTime() > maxMtime) { maxMtime = srcNode.status.getModificationTime(); } // attempt to repair all notFound nodes with srcNode // for (final MRNflyNode dstNode : mrNodes) { if (dstNode.status == null // not available || srcNode.compareTo(dstNode) == 0) { // same mtime continue; } try { // status is absolute from the underlying mount, making it chrooted // final FileStatus srcStatus = srcNode.cloneStatus(); srcStatus.setPath(f); final Path tmpPath = getNflyTmpPath(f); FileUtil.copy(srcNode.getFs(), srcStatus, dstNode.getFs(), tmpPath, false, // don't delete true, // overwrite getConf()); dstNode.getFs().delete(f, false); if (dstNode.getFs().rename(tmpPath, f)) { try { dstNode.getFs().setTimes(f, srcNode.status.getModificationTime(), srcNode.status.getAccessTime()); } finally { // save getFileStatus rpc srcStatus.setPath(dstNode.getFs().makeQualified(f)); dstNode.status = srcStatus; } } } catch (IOException ioe) { // can blame the source by statusSet.clear(ai), however, it would // cost an extra RPC, so just rely on the loop below that will attempt // an open anyhow // LOG.info(f + " " + srcNode + "->" + dstNode + ": Failed to repair", ioe); } } } // Since Java7, QuickSort is used instead of MergeSort. // QuickSort may not be stable and thus the equal most recent nodes, may no // longer appear in the NetworkTopology order. // if (maxMtime > 0) { final List mrList = new ArrayList(); for (final MRNflyNode openNode : mrNodes) { if (openNode.status != null && openNode.status.getLen() >= 0L) { if (openNode.status.getModificationTime() == maxMtime) { mrList.add(openNode); } } } // assert mrList.size > 0 final MRNflyNode[] readNodes = mrList.toArray(new MRNflyNode[0]); topology.sortByDistance(myNode, readNodes, readNodes.length); for (final MRNflyNode rNode : readNodes) { try { return rNode.getFs().open(f, bufferSize); } catch (IOException e) { LOG.info(f + ": Failed to open at " + rNode.getFs().getUri()); } } } return null; } private void mayThrowFileNotFound(List ioExceptions, int numNotFounds) throws FileNotFoundException { if (numNotFounds == nodes.length) { throw (FileNotFoundException)ioExceptions.get(nodes.length - 1); } } // WRITE @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return new FSDataOutputStream(new NflyOutputStream(f, permission, overwrite, bufferSize, replication, blockSize, progress), statistics); } // WRITE @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { return null; } // WRITE @Override public boolean rename(Path src, Path dst) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.rename(src, dst); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "rename", fnfe, ioExceptions, src, dst); } catch (Throwable t) { processThrowable(nflyNode, "rename", t, ioExceptions, src, dst); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } // WRITE @Override public boolean delete(Path f, boolean recursive) throws IOException { final List ioExceptions = new ArrayList(); int numNotFounds = 0; boolean succ = true; for (final NflyNode nflyNode : nodes) { try { succ &= nflyNode.fs.delete(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "delete", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "delete", t, ioExceptions, f); succ = false; } } mayThrowFileNotFound(ioExceptions, numNotFounds); // if all destinations threw exceptions throw, otherwise return // if (ioExceptions.size() == nodes.length) { throw MultipleIOException.createIOException(ioExceptions); } return succ; } /** * Returns the closest non-failing destination's result. * * @param f given path * @return array of file statuses according to nfly modes * @throws FileNotFoundException * @throws IOException */ @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final List ioExceptions = new ArrayList(nodes.length); final MRNflyNode[] mrNodes = workSet(); if (nflyFlags.contains(NflyKey.readMostRecent)) { int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { nflyNode.updateFileStatus(f); } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); Arrays.sort(mrNodes); } int numNotFounds = 0; for (final MRNflyNode nflyNode : mrNodes) { try { final FileStatus[] realStats = nflyNode.getFs().listStatus(f); final FileStatus[] nflyStats = new FileStatus[realStats.length]; for (int i = 0; i < realStats.length; i++) { nflyStats[i] = new NflyStatus(nflyNode.getFs(), realStats[i]); } return nflyStats; } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "listStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "listStatus", t, ioExceptions, f); } } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } @Override public RemoteIterator listLocatedStatus(Path f) throws FileNotFoundException, IOException { // TODO important for splits return super.listLocatedStatus(f); } @Override public void setWorkingDirectory(Path newDir) { for (final NflyNode nflyNode : nodes) { nflyNode.fs.setWorkingDirectory(newDir); } } @Override public Path getWorkingDirectory() { return nodes[0].fs.getWorkingDirectory(); // 0 is as good as any } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { boolean succ = true; for (final NflyNode nflyNode : nodes) { succ &= nflyNode.fs.mkdirs(f, permission); } return succ; } @Override public FileStatus getFileStatus(Path f) throws IOException { // TODO proxy stream for reads final List ioExceptions = new ArrayList(nodes.length); int numNotFounds = 0; final MRNflyNode[] mrNodes = workSet(); long maxMtime = Long.MIN_VALUE; int maxMtimeIdx = Integer.MIN_VALUE; // naively iterate until one can be returned // for (int i = 0; i < mrNodes.length; i++) { MRNflyNode nflyNode = mrNodes[i]; try { nflyNode.updateFileStatus(f); if (nflyFlags.contains(NflyKey.readMostRecent)) { final long nflyTime = nflyNode.status.getModificationTime(); if (nflyTime > maxMtime) { maxMtime = nflyTime; maxMtimeIdx = i; } } else { return nflyNode.nflyStatus(); } } catch (FileNotFoundException fnfe) { numNotFounds++; processThrowable(nflyNode, "getFileStatus", fnfe, ioExceptions, f); } catch (Throwable t) { processThrowable(nflyNode, "getFileStatus", t, ioExceptions, f); } } if (maxMtimeIdx >= 0) { return mrNodes[maxMtimeIdx].nflyStatus(); } mayThrowFileNotFound(ioExceptions, numNotFounds); throw MultipleIOException.createIOException(ioExceptions); } private static void processThrowable(NflyNode nflyNode, String op, Throwable t, List ioExceptions, Path... f) { final String errMsg = Arrays.toString(f) + ": failed to " + op + " " + nflyNode.fs.getUri(); final IOException ioex; if (t instanceof FileNotFoundException) { ioex = new FileNotFoundException(errMsg); ioex.initCause(t); } else { ioex = new IOException(errMsg, t); } if (ioExceptions != null) { ioExceptions.add(ioex); } } /** * Initializes an nfly mountpoint in viewfs. * * @param uris destinations to replicate writes to * @param conf file system configuration * @param settings comma-separated list of k=v pairs. * @return an Nfly filesystem * @throws IOException */ static FileSystem createFileSystem(URI[] uris, Configuration conf, String settings) throws IOException { // assert settings != null int minRepl = DEFAULT_MIN_REPLICATION; EnumSet nflyFlags = EnumSet.noneOf(NflyKey.class); final String[] kvPairs = StringUtils.split(settings); for (String kv : kvPairs) { final String[] kvPair = StringUtils.split(kv, '='); if (kvPair.length != 2) { throw new IllegalArgumentException(kv); } NflyKey nflyKey = NflyKey.valueOf(kvPair[0]); switch (nflyKey) { case minReplication: minRepl = Integer.parseInt(kvPair[1]); break; case repairOnRead: case readMostRecent: if (Boolean.valueOf(kvPair[1])) { nflyFlags.add(nflyKey); } break; default: throw new IllegalArgumentException(nflyKey + ": Infeasible"); } } return new NflyFSystem(uris, conf, minRepl, nflyFlags); } } |
blob | 1. long method, 2. blob | t | t | t | 1. long method | 0 | 9857 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NflyFSystem.java/#L60-L951 | 1 | 1105 | 9857 | minor | |
| 1008 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | long method | t | t | t | 0 | 9268 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1008 | 9268 | major | ||
| 5537 | { "answer": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Function keyFunction, Function valueFunction) { checkNotNull(keyFunction, "keyFunction"); checkNotNull(valueFunction, "valueFunction"); return Collector.of( ImmutableSetMultimap::builder, (builder, t) -> builder.put(keyFunction.apply(t), valueFunction.apply(t)), ImmutableSetMultimap.Builder::combine, ImmutableSetMultimap.Builder::build); } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 6246 | https://github.com/google/guava/blob/be92294be598b9b6ff0bd1cae3335759dafcb534/guava/src/com/google/common/collect/ImmutableSetMultimap.java/#L86-L96 | 2 | 5537 | 6246 | minor |
| 2666 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | long method | t | t | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 2666 | 15203 | major | ||
| 2405 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14386 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 2 | 2405 | 14386 | minor | ||
| 4023 | { "response": "YES, I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class ValueIterable implements Iterable { private ValueIterator iterator = new ValueIterator(); @Override public Iterator iterator() { return iterator; } } |
data class | long method, data class | t | t | t | long method | 0 | 10632 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/ReduceContextImpl.java/#L350-L356 | 1 | 4023 | 10632 | critical | |
| 1860 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12221 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 2 | 1860 | 12221 | minor | ||
| 2335 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | data class | t | t | t | 0 | 14161 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 2335 | 14161 | minor | ||
| 1132 | YES I found bad smells. the bad smells are: 1. Long method, 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static ConcurrentCompositeConfiguration createLocalConfig() { MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); if (localConfig.size() > 0) { ConfigModel model = new ConfigModel(); model.setConfig(localConfig); loader.getConfigModels().add(model); } LOGGER.info("create local config:"); for (ConfigModel configModel : loader.getConfigModels()) { LOGGER.info(" {}.", configModel.getUrl()); } ConcurrentCompositeConfiguration config = ConfigUtil.createLocalConfig(loader.getConfigModels()); ConfigUtil.setMicroserviceConfigLoader(config, loader); return config; } |
long method | Long method, 2 Repetitive code, 3 Feature envy, 4 Poor variable naming, 5 Poor use of static methods | t | f | t | 2. Repetitive code, 3. Feature envy, 4. Poor variable naming, 5. Poor use of static methods. | 0 | 10040 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigUtil.java/#L105-L122 | 2 | 1132 | 10040 | minor | |
| 899 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AssemblerConfig { // Private Member Variables ------------------------------------------------ /** The portlet app descriptor, which is usually WEB-INF/portlet.xml. */ private File portletDescriptor; /** The webapp descriptor to assemble, which is usually WEB-INF/web.xml. */ private File webappDescriptor; /** The assemble destination, which points to the assembled WAR file. */ private File destination; /** The class of the servlet that will handle portlet requests */ private String dispatchServletClass; /** The source archive to assemble */ private File source; /** Assembler sink buffer size. Defaults to 4096 bytes. */ private int assemblerSinkBuflen = 1024 * 4; // 4kb // Public Methods ---------------------------------------------------------- public File getPortletDescriptor() { return portletDescriptor; } public void setPortletDescriptor(File portletDescriptor) { this.portletDescriptor = portletDescriptor; } public File getWebappDescriptor() { return webappDescriptor; } public void setWebappDescriptor(File webappDescriptor) { this.webappDescriptor = webappDescriptor; } public File getDestination() { return destination; } public void setDestination(File destination) { this.destination = destination; } public String getDispatchServletClass() { return dispatchServletClass; } public void setDispatchServletClass(String dispatchServletClass) { this.dispatchServletClass = dispatchServletClass; } /** * @deprecated use setSource(File) instead. */ public void setWarSource(File source) { this.source = source; } public void setSource(File source) { this.source = source; } /** * @deprecated use getSource() instead. */ public File getWarSource() { return source; } public File getSource() { return source; } public int getAssemblerSinkBuflen() { return assemblerSinkBuflen; } public void setAssemblerSinkBuflen(int buflen) { this.assemblerSinkBuflen = buflen; } } |
data class | data class | t | t | t | 0 | 8152 | https://github.com/apache/portals-pluto/blob/4db5ddd26fb2ce642be7b0894858e664c6076a3b/pluto-util/src/main/java/org/apache/pluto/util/assemble/AssemblerConfig.java/#L25-L110 | 1 | 899 | 8152 | critical | ||
| 2446 | YES I found bad smellsThe bad smells are:1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void connected(SocketChannel channel) throws IOException, Exception { this.channel = channel; if( codec !=null ) { initializeCodec(); } this.channel.configureBlocking(false); this.remoteAddress = channel.socket().getRemoteSocketAddress().toString(); channel.socket().setSoLinger(true, 0); channel.socket().setTcpNoDelay(true); this.socketState = new CONNECTED(); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 14496 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/provider/fastbin/src/main/java/org/apache/aries/rsa/provider/fastbin/tcp/TcpTransport.java/#L150-L163 | 2 | 2446 | 14496 | minor | ||
| 448 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | long method | t | t | t | 0 | 4366 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 1 | 448 | 4366 | minor | ||
| 5713 | Yes, I found bad smells. The bad smells are: 1. Long method, 2.Feature Envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Long method, 2Feature Envy | t | f | t | 2.Feature Envy | 0 | 12782 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5713 | 12782 | critical | |
| 148 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Attachment { private String fallback; private String color; private String pretext; private String authorName; private String authorLink; private String authorIcon; private String title; private String titleLink; private String text; private String imageUrl; private String thumbUrl; private String footer; private String footerIcon; private Long ts; private List fields; public String getFallback() { return fallback; } public void setFallback(String fallback) { this.fallback = fallback; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getPretext() { return pretext; } public void setPretext(String pretext) { this.pretext = pretext; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorLink() { return authorLink; } public void setAuthorLink(String authorLink) { this.authorLink = authorLink; } public String getAuthorIcon() { return authorIcon; } public void setAuthorIcon(String authorIcon) { this.authorIcon = authorIcon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTitleLink() { return titleLink; } public void setTitleLink(String titleLink) { this.titleLink = titleLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getFooter() { return footer; } public void setFooter(String footer) { this.footer = footer; } public String getFooterIcon() { return footerIcon; } public void setFooterIcon(String footerIcon) { this.footerIcon = footerIcon; } public Long getTs() { return ts; } public void setTs(Long ts) { this.ts = ts; } public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; } public class Field { private String title; private String value; private Boolean shortValue; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Boolean isShortValue() { return shortValue; } public void setShortValue(Boolean shortValue) { this.shortValue = shortValue; } } } |
data class | data class | t | t | t | 0 | 1844 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-slack/src/main/java/org/apache/camel/component/slack/helper/SlackMessage.java/#L78-L241 | 1 | 148 | 1844 | major | ||
| 1572 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { Map dm = new HashMap(); dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); dm.put(ApiConstants.S3_END_POINT, getEndPoint()); dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); if (getSigner() != null && (getSigner().equals(ApiConstants.S3_V3_SIGNER) || getSigner().equals(ApiConstants.S3_V4_SIGNER))) { dm.put(ApiConstants.S3_SIGNER, getSigner()); } if (isHttps() != null) { dm.put(ApiConstants.S3_HTTPS_FLAG, isHttps().toString()); } if (getConnectionTimeout() != null) { dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); } if (getMaxErrorRetry() != null) { dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); } if (getSocketTimeout() != null) { dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); } if (getConnectionTtl() != null) { dm.put(ApiConstants.S3_CONNECTION_TTL, getConnectionTtl().toString()); } if (getUseTCPKeepAlive() != null) { dm.put(ApiConstants.S3_USE_TCP_KEEPALIVE, getUseTCPKeepAlive().toString()); } try{ ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11341 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java/#L99-L147 | 2 | 1572 | 11341 | minor | |
| 2217 | {"message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Sampler deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); String type = node.get("type").asText(); switch (type) { case "uniform": { double lowerBound = node.get("lower").asDouble(); double upperBound = node.get("upper").asDouble(); checkArgument( lowerBound >= 0, "The lower bound of uniform distribution should be a non-negative number, " + "but found %s.", lowerBound); return fromRealDistribution(new UniformRealDistribution(lowerBound, upperBound)); } case "exp": { double mean = node.get("mean").asDouble(); return fromRealDistribution(new ExponentialDistribution(mean)); } case "normal": { double mean = node.get("mean").asDouble(); double stddev = node.get("stddev").asDouble(); checkArgument( mean >= 0, "The mean of normal distribution should be a non-negative number, but found %s.", mean); return fromRealDistribution(new NormalDistribution(mean, stddev)); } case "const": { double constant = node.get("const").asDouble(); checkArgument( constant >= 0, "The value of constant distribution should be a non-negative number, but found %s.", constant); return fromRealDistribution(new ConstantRealDistribution(constant)); } case "zipf": { double param = node.get("param").asDouble(); final double multiplier = node.has("multiplier") ? node.get("multiplier").asDouble() : 1.0; checkArgument( param > 1, "The parameter of the Zipf distribution should be > 1, but found %s.", param); checkArgument( multiplier >= 0, "The multiplier of the Zipf distribution should be >= 0, but found %s.", multiplier); final ZipfDistribution dist = new ZipfDistribution(100, param); return scaledSampler(fromIntegerDistribution(dist), multiplier); } default: { throw new IllegalArgumentException("Unknown distribution type: " + type); } } } |
long method | long method, data class | t | t | t | data class | 0 | 13539 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/io/synthetic/src/main/java/org/apache/beam/sdk/io/synthetic/SyntheticOptions.java/#L228-L289 | 1 | 2217 | 13539 | major | |
| 2535 | YES I found bad smells the bad smells are: 1.Long method, 2.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | Long method, 2Conditional complexity | t | f | t | 2.Conditional complexity | 0 | 14753 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 2535 | 14753 | minor | |
| 1379 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 10817 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 1379 | 10817 | critical | ||
| 1345 | YES, I found bad smells the bad smells are: 1.Long method, 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method, 2Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind This code is tightly coupled 3Magic numbers: Type IDs like testITgetTypeID() make the code less readable | t | f | t | 2.Feature envy: unnecessary dependency on other classes such as SequenceType, Quantifier, ItemType, AnyItemType, AtomicType, BuiltinTypeRegistry, SchemaType, NodeType, NodeKind. This code is tightly coupled. 3.Magic numbers: Type IDs like testIT.getTypeID() make the code less readable. | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1345 | 10747 | minor | |
| 2426 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method, 2Magic numbers, 3Nested conditionals, 4Method chain, 5Inappropriate naming, 6Duplicated code, 7Complexity, 8Poor exception handling | t | f | t | 2.Magic numbers, 3.Nested conditionals, 4.Method chain, 5.Inappropriate naming, 6.Duplicated code, 7.Complexity, 8.Poor exception handling. | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 2426 | 14445 | minor | |
| 914 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | 'Long Method', 'Data Class' | t | t | f | {',L,o,n,g," ",M,e,t,h,o,d,',","," ",',D,a,t,a," ",C,l,a,s,s,'} | {',o,n,g," ",M,t,h,o,d,',","," ",',D,t," ",C,'} | 0 | 8245 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 914 | 8245 | critical |
| 2341 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final class AvlNode> { AvlNode parent = null; AvlNode left = null; AvlNode right = null; int height = 0; int balance = 0; T value = null; AvlNode( AvlNode parent, T value ) { this.parent = parent; this.value = value; } public AvlNode reset( AvlNode parent, T value ) { this.parent = parent; left = null; right = null; height = 0; this.value = value; return this; } } |
data class | blob, data class | t | t | t | blob | 0 | 14178 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/core-avl/src/main/java/org/apache/directory/server/core/avltree/avl/AvlNode.java/#L29-L58 | 1 | 2341 | 14178 | minor | |
| 1163 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10179 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 1 | 1163 | 10179 | minor | |
| 2078 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13053 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 2078 | 13053 | minor | ||
| 1227 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1227 | 10353 | major | ||
| 117 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | blob, data class | t | t | t | blob | 0 | 1507 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 1 | 117 | 1507 | minor | |
| 5481 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.util.concurrent.Future updateStack( final UpdateStackRequest request, final com.oracle.bmc.responses.AsyncHandler handler) { LOG.trace("Called async updateStack"); final UpdateStackRequest interceptedRequest = UpdateStackConverter.interceptRequest(request); final com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = UpdateStackConverter.fromRequest(client, interceptedRequest); final com.google.common.base.Function transformer = UpdateStackConverter.fromResponse(); com.oracle.bmc.responses.AsyncHandler handlerToUse = handler; if (handler != null && this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { handlerToUse = new com.oracle.bmc.util.internal.RefreshAuthTokenWrappingAsyncHandler< UpdateStackRequest, UpdateStackResponse>( (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, handler) { @Override public void retryCall() { final com.oracle.bmc.util.internal.Consumer onSuccess = new com.oracle.bmc.http.internal.SuccessConsumer<>( this, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = new com.oracle.bmc.http.internal.ErrorConsumer<>( this, interceptedRequest); client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }; } final com.oracle.bmc.util.internal.Consumer onSuccess = (handler == null) ? null : new com.oracle.bmc.http.internal.SuccessConsumer<>( handlerToUse, transformer, interceptedRequest); final com.oracle.bmc.util.internal.Consumer onError = (handler == null) ? null : new com.oracle.bmc.http.internal.ErrorConsumer<>( handlerToUse, interceptedRequest); java.util.concurrent.Future responseFuture = client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); if (this.authenticationDetailsProvider instanceof com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) { return new com.oracle.bmc.util.internal.RefreshAuthTokenTransformingFuture< javax.ws.rs.core.Response, UpdateStackResponse>( responseFuture, transformer, (com.oracle.bmc.auth.RefreshableOnNotAuthenticatedProvider) this.authenticationDetailsProvider, new com.google.common.base.Supplier< java.util.concurrent.Future>() { @Override public java.util.concurrent.Future get() { return client.put( ib, interceptedRequest.getUpdateStackDetails(), interceptedRequest, onSuccess, onError); } }); } else { return new com.oracle.bmc.util.internal.TransformingFuture<>( responseFuture, transformer); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 1263 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-resourcemanager/src/main/java/com/oracle/bmc/resourcemanager/ResourceManagerAsyncClient.java/#L1366-L1452 | 1 | 5481 | 1263 | major | |
| 2488 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data Class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected class UnifyRuleCall { protected final UnifyRule rule; public final MutableRel query; public final MutableRel target; protected final ImmutableList slots; public UnifyRuleCall(UnifyRule rule, MutableRel query, MutableRel target, ImmutableList slots) { this.rule = Objects.requireNonNull(rule); this.query = Objects.requireNonNull(query); this.target = Objects.requireNonNull(target); this.slots = Objects.requireNonNull(slots); } public UnifyResult result(MutableRel result) { assert MutableRels.contains(result, target); assert equalType("result", result, "query", query, Litmus.THROW); MutableRel replace = replacementMap.get(target); if (replace != null) { assert false; // replacementMap is always empty // result = replace(result, target, replace); } register(result, query); return new UnifyResult(this, result); } /** * Creates a {@link UnifyRuleCall} based on the parent of {@code query}. */ public UnifyRuleCall create(MutableRel query) { return new UnifyRuleCall(rule, query, target, slots); } public RelOptCluster getCluster() { return cluster; } public RexSimplify getSimplify() { return simplify; } } |
data class | 1: data class | t | t | t | 0 | 14613 | https://github.com/apache/calcite/blob/a648f9c12309cc253628930b0cab98591caa66ab/core/src/main/java/org/apache/calcite/plan/SubstitutionVisitor.java/#L854-L896 | 1 | 2488 | 14613 | minor | ||
| 1840 | YES I found bad smells: 1. Long method, 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | Long method, 2 Magic number, 3 Feature envy, 4 Duplicate code: LOGinfo statements, 5 Redundant code: null check for dirRoot, 6 Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7 Lack of clear separation of concerns: mixing of logging and crawling functionality, 8 Lack of proper error handling and exception handling | t | f | t | 2. Magic number, 3. Feature envy, 4. Duplicate code: LOG.info statements, 5. Redundant code: null check for dirRoot, 6. Magic strings: "Start crawling dir:", "Crawling", "Finished crawling dir:", 7. Lack of clear separation of concerns: mixing of logging and crawling functionality, 8. Lack of proper error handling and exception handling. | 0 | 12149 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 2 | 1840 | 12149 | minor | |
| 528 | { "message": "YES I found bad smells", "detected_bad_smells": { "the_bad_smells_are": [ "Long Method", "Feature Envy" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | the_bad_smells_are: long method, feature envy | t | t | f | the_bad_smells_are: long method | feature envy | 0 | 5451 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 528 | 5451 | minor |
| 1981 | { "message": "YES I found bad smells", "bad_smells": [ { "1": "Data Class" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PageExtractor { private PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage = 0; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (inclusive) * @param endPage The last page you want extracted (inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this(sourceDocument); this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog().setViewerPreferences( sourceDocument.getDocumentCatalog().getViewerPreferences()); for (int i = startPage; i <= endPage; i++) { PDPage page = sourceDocument.getPage(i - 1); PDPage imported = extractedDocument.importPage(page); imported.setCropBox(page.getCropBox()); imported.setMediaBox(page.getMediaBox()); imported.setResources(page.getResources()); imported.setRotation(page.getRotation()); } return extractedDocument; } /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } } |
data class | 1: data class, 2: long method | t | t | f | 2: long method | data class | 0 | 12639 | https://github.com/apache/pdfbox/blob/443b7dd95c57bc83598c8c5d514ebb44a4133a43/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java/#L28-L127 | 1 | 1981 | 12639 | minor |
| 1183 | YES, I found bad smells: 1. Feature envy 2. Duplicate code 3. Long method 4. Data class 5. Lazy class 6. Large class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | Feature envy 2 Duplicate code 3 Long method 4 Data class 5 Lazy class 6 Large class | t | f | t | 0 | 10238 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 2 | 1183 | 10238 | major | ||
| 1927 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public short syncAll(short syncMode) { short syncState = SYNC_STATE_IN_SYNC; /* vnc classes need to be synchronized with cloudstack */ s_logger.debug("syncing cloudstack db with vnc"); try { for (Class cls : _vncClasses) { /* lock the sync mode*/ _lockSyncMode.lock(); _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); } if (_dbSync.sync(cls) == false) { if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); } syncState = SYNC_STATE_OUT_OF_SYNC; } if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { s_logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); } else { s_logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); } /* unlock the sync mode */ _lockSyncMode.unlock(); } } catch (Exception ex) { s_logger.warn("DB Synchronization", ex); syncState = SYNC_STATE_UNKNOWN; if (_lockSyncMode.isLocked()) { _lockSyncMode.unlock(); } } return syncState; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 12439 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java/#L129-L174 | 1 | 1927 | 12439 | minor |
| 959 | { "output": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: BundleArchiveRevision(String location, File revisionDir, File file) throws IOException{ this.revisionDir = revisionDir; this.location = location; if (!this.revisionDir.exists()) { this.revisionDir.mkdirs(); } if(revisionDir.getAbsolutePath().startsWith(RuntimeVariables.androidApplication.getFilesDir().getAbsolutePath())){ externalStorage = false; }else{ externalStorage = true; } if(shouldCopyInstallFile(file)){ if (isSameDriver(revisionDir, file)) { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); boolean result = file.renameTo(bundleFile); if(!result){ ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } } else { this.revisionLocation = FILE_PROTOCOL; this.bundleFile = new File(revisionDir, BUNDLE_FILE_NAME); ApkUtils.copyInputStreamToFile(new FileInputStream(file), bundleFile); } installSoLib(bundleFile); }else{ this.revisionLocation = REFERENCE_PROTOCOL + file.getAbsolutePath(); this.bundleFile = file; installSoLib(file); } updateMetadata(); } |
long method | 1. long method | t | t | t | 0 | 8560 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-core/src/main/java/android/taobao/atlas/framework/bundlestorage/BundleArchiveRevision.java/#L301-L332 | 1 | 959 | 8560 | minor | ||
| 1922 | JSE I found bad smells: 1. Long method 2. Feature envy 3. Data class 4. Indecent exposure 5. Complexity 6. Shotgun surgery 7. Inappropriate Intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public abstract class ShareContent implements ShareModel { private final Uri contentUrl; private final List peopleIds; private final String placeId; private final String pageId; private final String ref; private final ShareHashtag hashtag; protected ShareContent(final Builder builder) { super(); this.contentUrl = builder.contentUrl; this.peopleIds = builder.peopleIds; this.placeId = builder.placeId; this.pageId = builder.pageId; this.ref = builder.ref; this.hashtag = builder.hashtag; } protected ShareContent(final Parcel in) { this.contentUrl = in.readParcelable(Uri.class.getClassLoader()); this.peopleIds = readUnmodifiableStringList(in); this.placeId = in.readString(); this.pageId = in.readString(); this.ref = in.readString(); this.hashtag = new ShareHashtag.Builder().readFrom(in).build(); } /** * URL for the content being shared. This URL will be checked for app link meta tags for * linking in platform specific ways. * * See documentation for App Links. * * @return {@link android.net.Uri} representation of the content link. */ @Nullable public Uri getContentUrl() { return this.contentUrl; } /** * List of Ids for taggable people to tag with this content. * * See documentation for * * Taggable Friends. * * @return {@link java.util.List} of Ids for people to tag. */ @Nullable public List getPeopleIds() { return this.peopleIds; } /** * The Id for a place to tag with this content. * * @return The Id for the place to tag. */ @Nullable public String getPlaceId() { return this.placeId; } /** * For shares into Messenger, this pageID will be used to map the app to page and attach * attribution to the share. * * @return The ID of the Facebook page this share is associated with. */ @Nullable public String getPageId() { return this.pageId; } /** * A value to be added to the referrer URL when a person follows a link from this shared * content on feed. * * @return The ref for the content. */ @Nullable public String getRef() { return this.ref; } /** * Gets the ShareHashtag, if one has been set, for this content. * * @return The hashtag */ @Nullable public ShareHashtag getShareHashtag() { return this.hashtag; } public int describeContents() { return 0; } public void writeToParcel(final Parcel out, final int flags) { out.writeParcelable(this.contentUrl, 0); out.writeStringList(this.peopleIds); out.writeString(this.placeId); out.writeString(this.pageId); out.writeString(this.ref); out.writeParcelable(this.hashtag, 0); } private List readUnmodifiableStringList(final Parcel in) { final List list = new ArrayList(); in.readStringList(list); return (list.size() == 0 ? null : Collections.unmodifiableList(list)); } /** * Abstract builder for {@link com.facebook.share.model.ShareContent} */ public abstract static class Builder implements ShareModelBuilder { private Uri contentUrl; private List peopleIds; private String placeId; private String pageId; private String ref; private ShareHashtag hashtag; /** * Set the URL for the content being shared. * * @param contentUrl {@link android.net.Uri} representation of the content link. * @return The builder. */ public E setContentUrl(@Nullable final Uri contentUrl) { this.contentUrl = contentUrl; return (E) this; } /** * Set the list of Ids for taggable people to tag with this content. * * @param peopleIds {@link java.util.List} of Ids for people to tag. * @return The builder. */ public E setPeopleIds(@Nullable final List peopleIds) { this.peopleIds = (peopleIds == null ? null : Collections.unmodifiableList(peopleIds)); return (E) this; } /** * Set the Id for a place to tag with this content. * * @param placeId The Id for the place to tag. * @return The builder. */ public E setPlaceId(@Nullable final String placeId) { this.placeId = placeId; return (E) this; } /** * Set the Id of the Facebook page this share is associated with. * * @param pageId The Id for the Page * @return The builder */ public E setPageId(@Nullable final String pageId) { this.pageId = pageId; return (E) this; } /** * Set the value to be added to the referrer URL when a person follows a link from this * shared content on feed. * * @param ref The ref for the content. * @return The builder. */ public E setRef(@Nullable final String ref) { this.ref = ref; return (E) this; } /** * Set the ShareHashtag for this content * * @param shareHashtag The hashtag for this content * @return The builder */ public E setShareHashtag(@Nullable final ShareHashtag shareHashtag) { this.hashtag = shareHashtag; return (E) this; } @Override public E readFrom(final P content) { if (content == null) { return (E) this; } return (E) this .setContentUrl(content.getContentUrl()) .setPeopleIds(content.getPeopleIds()) .setPlaceId(content.getPlaceId()) .setPageId(content.getPageId()) .setRef(content.getRef()); } } } |
data class | Long method2 Feature envy3 Data class4 Indecent exposure5 Complexity6 Shotgun surgery7 Inappropriate Intimacy | f | f | t | 0 | 12425 | https://github.com/facebook/facebook-android-sdk/blob/81ca34a2a0f7ee391f90c6051c5a22e5bc8663c2/facebook-common/src/main/java/com/facebook/share/model/ShareContent.java/#L35-L243 | 2 | 1922 | 12425 | major | ||
| 505 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void unitKept(IInstallableUnit unit) { super.unitKept(unit); logger.debug(" Keeping unit " + unit.getId() + "/" + unit.getVersion()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5129 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-bundles/org.eclipse.tycho.p2.resolver.impl/src/main/java/org/eclipse/tycho/p2/target/filters/TargetPlatformFilterEvaluator.java/#L287-L291 | 2 | 505 | 5129 | major | ||
| 374 | YES I found bad smells, the bad smells are: 1. Long method, 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Magic strings, 3 Multiple statements per line, 4 Duplicate code, 5 Non-descriptive variable names, 6 Hard-coded values, 7 Poorly structured code, 8 Feature envy | t | f | t | 2. Magic strings, 3. Multiple statements per line, 4. Duplicate code, 5. Non-descriptive variable names, 6. Hard-coded values, 7. Poorly structured code, 8. Feature envy. | 0 | 3864 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 374 | 3864 | major | |
| 5585 | YES I found bad smells: Long method, Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void finishRestore(final Timer.Context context, Map> commitToStats, List commitsToRollback, final String startRestoreTime, final String restoreToInstant) throws IOException { HoodieTable table = HoodieTable.getHoodieTable( new HoodieTableMetaClient(jsc.hadoopConfiguration(), config.getBasePath(), true), config, jsc); Optional durationInMs = Optional.empty(); Long numFilesDeleted = 0L; for (Map.Entry> commitToStat : commitToStats.entrySet()) { List stats = commitToStat.getValue(); numFilesDeleted = stats.stream().mapToLong(stat -> stat.getSuccessDeleteFiles().size()) .sum(); } if (context != null) { durationInMs = Optional.of(metrics.getDurationInMs(context.stop())); metrics.updateRollbackMetrics(durationInMs.get(), numFilesDeleted); } HoodieRestoreMetadata restoreMetadata = AvroUtils .convertRestoreMetadata(startRestoreTime, durationInMs, commitsToRollback, commitToStats); table.getActiveTimeline().saveAsComplete( new HoodieInstant(true, HoodieTimeline.RESTORE_ACTION, startRestoreTime), AvroUtils.serializeRestoreMetadata(restoreMetadata)); logger.info("Commits " + commitsToRollback + " rollback is complete. Restored dataset to " + restoreToInstant); if (!table.getActiveTimeline().getCleanerTimeline().empty()) { logger.info("Cleaning up older restore meta files"); // Cleanup of older cleaner meta files // TODO - make the commit archival generic and archive rollback metadata FSUtils.deleteOlderRollbackMetaFiles(fs, table.getMetaClient().getMetaPath(), table.getActiveTimeline().getRestoreTimeline().getInstants()); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 9277 | https://github.com/apache/incubator-hudi/blob/194d904c99ebd013af55eac7509e3e79193dce77/hoodie-client/src/main/java/com/uber/hoodie/HoodieWriteClient.java/#L928-L957 | 1 | 5585 | 9277 | major | |
| 2427 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14446 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 2427 | 14446 | minor | |
| 2523 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14713 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fo/flow/Leader.java/#L72-L106 | 2 | 2523 | 14713 | minor | ||
| 2260 | YES, I found bad smells the bad smells are: 1. Commented out code 2. Multiple nested if-else statements 3. Use of instanceof operator 4. Use of a switch statement 5. Duplicate code 6. Naming conventions not followed (method name should be in lower camel case) 7. Inconsistent formatting/spacing 8. Long method (more than 10 lines of code) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Commented out code2 Multiple nested if-else statements3 Use of instanceof operator4 Use of a switch statement5 Duplicate code6 Naming conventions not followed (method name should be in lower camel case)7 Inconsistent formatting/spacing8 Long method (more than | t | f | t | 0 | 13711 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 2260 | 13711 | minor | ||
| 1452 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11001 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1452 | 11001 | minor | ||
| 1878 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | long method | t | t | t | 0 | 12273 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 1 | 1878 | 12273 | minor | ||
| 2185 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 13430 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 2185 | 13430 | major | |
| 1179 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 1179 | 10227 | critical | ||
| 537 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 5493 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 537 | 5493 | minor | ||
| 5777 | YES I found bad smells the bad smells are: 1. Long Method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | Long Method | t | f | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 1 | 5777 | 15213 | minor | ||
| 755 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected MqttDeliveryToken restoreToken(MqttPublish message) { final String methodName = "restoreToken"; MqttDeliveryToken token; synchronized(tokens) { String key = Integer.toString(message.getMessageId()); if (this.tokens.containsKey(key)) { token = (MqttDeliveryToken)this.tokens.get(key); //@TRACE 302=existing key={0} message={1} token={2} log.fine(CLASS_NAME,methodName, "302",new Object[]{key, message,token}); } else { token = new MqttDeliveryToken(logContext); token.internalTok.setKey(key); this.tokens.put(key, token); //@TRACE 303=creating new token key={0} message={1} token={2} log.fine(CLASS_NAME,methodName,"303",new Object[]{key, message, token}); } } return token; } |
long method | blob, data class, long method | t | t | t | blob, data class | 0 | 7047 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/internal/CommsTokenStore.java/#L108-L126 | 1 | 755 | 7047 | minor | |
| 1424 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class MacOSXSocketOptions extends PlatformSocketOptions { public MacOSXSocketOptions() { } @Override boolean keepAliveOptionsSupported() { return keepAliveOptionsSupported0(); } @Override void setTcpkeepAliveProbes(int fd, final int value) throws SocketException { setTcpkeepAliveProbes0(fd, value); } @Override void setTcpKeepAliveTime(int fd, final int value) throws SocketException { setTcpKeepAliveTime0(fd, value); } @Override void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException { setTcpKeepAliveIntvl0(fd, value); } @Override int getTcpkeepAliveProbes(int fd) throws SocketException { return getTcpkeepAliveProbes0(fd); } @Override int getTcpKeepAliveTime(int fd) throws SocketException { return getTcpKeepAliveTime0(fd); } @Override int getTcpKeepAliveIntvl(int fd) throws SocketException { return getTcpKeepAliveIntvl0(fd); } private static native void setTcpkeepAliveProbes0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveTime0(int fd, int value) throws SocketException; private static native void setTcpKeepAliveIntvl0(int fd, int value) throws SocketException; private static native int getTcpkeepAliveProbes0(int fd) throws SocketException; private static native int getTcpKeepAliveTime0(int fd) throws SocketException; private static native int getTcpKeepAliveIntvl0(int fd) throws SocketException; private static native boolean keepAliveOptionsSupported0(); static { AccessController.doPrivileged((PrivilegedAction) () -> { System.loadLibrary("extnet"); return null; }); } } |
data class | Data Class | t | f | t | 0 | 10935 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.net/macosx/classes/jdk/net/MacOSXSocketOptions.java/#L32-L85 | 1 | 1424 | 10935 | major | ||
| 1537 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11223 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 2 | 1537 | 11223 | major | ||
| 2203 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | long method, data class | t | t | t | data class | 0 | 13507 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 1 | 2203 | 13507 | critical | |
| 1322 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | long method | t | t | t | 0 | 10699 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 1 | 1322 | 10699 | major | ||
| 1845 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method, 2 Feature envy, 3 Indecent Exposure, 4 Drill-down, 5 Inappropriate Intimacy, 6 Temporary Field, 7 Large Class | t | f | t | 2. Feature envy, 3. Indecent Exposure, 4. Drill-down, 5. Inappropriate Intimacy, 6. Temporary Field, 7. Large Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 1845 | 12164 | major | |
| 1923 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | long method | t | t | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 1 | 1923 | 12426 | minor | ||
| 1619 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 1619 | 11477 | minor | |
| 1879 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public final class CompactCharArray implements Cloneable { /** * The total number of Unicode characters. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int UNICODECOUNT = 65536; /** * Default constructor for CompactCharArray, the default value of the * compact array is 0. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray() { this((char)0); } /** * Constructor for CompactCharArray. * @param defaultValue the default value of the compact array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(char defaultValue) { int i; values = new char[UNICODECOUNT]; indices = new char[INDEXCOUNT]; hashes = new int[INDEXCOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { values[i] = defaultValue; } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<= newValues.length+BLOCKCOUNT) throw new IllegalArgumentException("Index out of bounds."); } indices = indexArray; values = newValues; isCompact = true; } /** * Constructor for CompactCharArray. * * @param indexArray the RLE-encoded indicies of the compact array. * @param valueArray the RLE-encoded values of the compact array. * * @throws IllegalArgumentException if the index or value array is * the wrong size. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public CompactCharArray(String indexArray, String valueArray) { this( Utility.RLEStringToCharArray(indexArray), Utility.RLEStringToCharArray(valueArray)); } /** * Get the mapped value of a Unicode character. * @param index the character to get the mapped value with * @return the mapped value of the given character * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char elementAt(char index) { int ix = (indices[index >> BLOCKSHIFT] & 0xFFFF) + (index & BLOCKMASK); return ix >= values.length ? defaultValue : values[ix]; } /** * Set a new value for a Unicode character. * Set automatically expands the array if it is compacted. * @param index the character to set the mapped value with * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char index, char value) { if (isCompact) expand(); values[index] = value; touchBlock(index >> BLOCKSHIFT, value); } /** * Set new values for a range of Unicode character. * * @param start the starting offset of the range * @param end the ending offset of the range * @param value the new mapped value * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void setElementAt(char start, char end, char value) { int i; if (isCompact) { expand(); } for (i = start; i <= end; ++i) { values[i] = value; touchBlock(i >> BLOCKSHIFT, value); } } /** * Compact the array * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact() { compact(true); } /** * Compact the array. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public void compact(boolean exhaustive) { if (!isCompact) { int iBlockStart = 0; char iUntouched = 0xFFFF; int newSize = 0; char[] target = exhaustive ? new char[UNICODECOUNT] : values; for (int i = 0; i < indices.length; ++i, iBlockStart += BLOCKCOUNT) { indices[i] = 0xFFFF; boolean touched = blockTouched(i); if (!touched && iUntouched != 0xFFFF) { // If no values in this block were set, we can just set its // index to be the same as some other block with no values // set, assuming we've seen one yet. indices[i] = iUntouched; } else { int jBlockStart = 0; // See if we can find a previously compacted block that's identical for (int j = 0; j < i; ++j, jBlockStart += BLOCKCOUNT) { if (hashes[i] == hashes[j] && arrayRegionMatches(values, iBlockStart, values, jBlockStart, BLOCKCOUNT)) { indices[i] = indices[j]; } } if (indices[i] == 0xFFFF) { int dest; // Where to copy if (exhaustive) { // See if we can find some overlap with another block dest = FindOverlappingPosition(iBlockStart, target, newSize); } else { // Just copy to the end; it's quicker dest = newSize; } int limit = dest + BLOCKCOUNT; if (limit > newSize) { for (int j = newSize; j < limit; ++j) { target[j] = values[iBlockStart + j - dest]; } newSize = limit; } indices[i] = (char)dest; if (!touched) { // If this is the first untouched block we've seen, // remember its index. iUntouched = (char)jBlockStart; } } } } // we are done compacting, so now make the array shorter char[] result = new char[newSize]; System.arraycopy(target, 0, result, 0, newSize); values = result; isCompact = true; hashes = null; } } private int FindOverlappingPosition(int start, char[] tempValues, int tempCount) { for (int i = 0; i < tempCount; i += 1) { int currentCount = BLOCKCOUNT; if (i + BLOCKCOUNT > tempCount) { currentCount = tempCount - i; } if (arrayRegionMatches(values, start, tempValues, i, currentCount)) return i; } return tempCount; } /** * Convenience utility to compare two arrays of doubles. * @param len the length to compare. * The start indices and start+len must be valid. */ final static boolean arrayRegionMatches(char[] source, int sourceStart, char[] target, int targetStart, int len) { int sourceEnd = sourceStart + len; int delta = targetStart - sourceStart; for (int i = sourceStart; i < sourceEnd; i++) { if (source[i] != target[i + delta]) return false; } return true; } /** * Remember that a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final void touchBlock(int i, int value) { hashes[i] = (hashes[i] + (value<<1)) | 1; } /** * Query whether a specified block was "touched", i.e. had a value set. * Untouched blocks can be skipped when compacting the array */ private final boolean blockTouched(int i) { return hashes[i] != 0; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getIndexArray() { return indices; } /** * For internal use only. Do not modify the result, the behavior of * modified results are undefined. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public char[] getValueArray() { return values; } /** * Overrides Cloneable * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public Object clone() { try { CompactCharArray other = (CompactCharArray) super.clone(); other.values = values.clone(); other.indices = indices.clone(); if (hashes != null) other.hashes = hashes.clone(); return other; } catch (CloneNotSupportedException e) { throw new ICUCloneNotSupportedException(e); } } /** * Compares the equality of two compact array objects. * @param obj the compact array object to be compared with this. * @return true if the current compact array object is the same * as the compact array object obj; false otherwise. * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) // quick check return true; if (getClass() != obj.getClass()) // same class? return false; CompactCharArray other = (CompactCharArray) obj; for (int i = 0; i < UNICODECOUNT; i++) { // could be sped up later if (elementAt((char)i) != other.elementAt((char)i)) return false; } return true; // we made it through the guantlet. } /** * Generates the hash code for the compact array object * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Override @Deprecated public int hashCode() { int result = 0; int increment = Math.min(3, values.length/16); for (int i = 0; i < values.length; i+= increment) { result = result * 37 + values[i]; } return result; } // -------------------------------------------------------------- // private // -------------------------------------------------------------- /** * Expanding takes the array back to a 65536 element array. */ private void expand() { int i; if (isCompact) { char[] tempArray; hashes = new int[INDEXCOUNT]; tempArray = new char[UNICODECOUNT]; for (i = 0; i < UNICODECOUNT; ++i) { tempArray[i] = elementAt((char)i); } for (i = 0; i < INDEXCOUNT; ++i) { indices[i] = (char)(i<<BLOCKSHIFT); } values = null; values = tempArray; isCompact = false; } } /** * @deprecated This API is ICU internal only. * @hide draft / provisional / internal are hidden on Android */ @Deprecated public static final int BLOCKSHIFT = 5; // NormalizerBuilder needs - liu static final int BLOCKCOUNT =(1<<BLOCKSHIFT); static final int INDEXSHIFT =(16-BLOCKSHIFT); static final int INDEXCOUNT =(1<<INDEXSHIFT); static final int BLOCKMASK = BLOCKCOUNT - 1; private char values[]; private char indices[]; private int[] hashes; private boolean isCompact; char defaultValue; } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 12276 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/CompactCharArray.java/#L37-L434 | 1 | 1879 | 12276 | critical | |
| 2518 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void main(String[] args) throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet("linechart"); final int NUM_OF_ROWS = 3; final int NUM_OF_COLUMNS = 10; // Create a row and put some cells in it. Rows are 0 based. Row row; Cell cell; for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { row = sheet.createRow((short) rowIndex); for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { cell = row.createCell((short) colIndex); cell.setCellValue(colIndex * (rowIndex + 1.0)); } } XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); XSSFChart chart = drawing.createChart(anchor); XDDFChartLegend legend = chart.getOrAddLegend(); legend.setPosition(LegendPosition.TOP_RIGHT); // Use a category axis for the bottom axis. XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765 XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("f(x)"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); XDDFNumericalDataSource ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1); series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842 series1.setSmooth(false); // https://stackoverflow.com/questions/29014848 series1.setMarkerStyle(MarkerStyle.STAR); // https://stackoverflow.com/questions/39636138 XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2); series2.setTitle("3x", null); series2.setSmooth(true); series2.setMarkerSize((short) 6); series2.setMarkerStyle(MarkerStyle.TRIANGLE); // https://stackoverflow.com/questions/39636138 chart.plot(data); // if your series have missing values like https://stackoverflow.com/questions/29014848 // chart.displayBlanksAs(DisplayBlanks.GAP); // https://stackoverflow.com/questions/24676460 solidLineSeries(data, 0, PresetColor.CHARTREUSE); solidLineSeries(data, 1, PresetColor.TURQUOISE); // Write the output to a file try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) { wb.write(fileOut); } } } |
long method | long method, data class | t | t | t | data class | 0 | 14704 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java/#L54-L113 | 1 | 2518 | 14704 | major | |
| 1620 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class FieldSchemaWrapper { @JsonIgnore private FieldSchema fieldSchema; @JsonProperty public String name; @JsonProperty public String type; @JsonProperty public String comment; @JsonCreator public FieldSchemaWrapper(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("comment") String comment) { this.name = name; this.type = type; this.comment = comment; this.fieldSchema = new FieldSchema(name, type, comment); } public FieldSchemaWrapper(FieldSchema fieldSchema) { this.fieldSchema = fieldSchema; this.name = fieldSchema.getName(); this.type = fieldSchema.getType(); this.comment = fieldSchema.getComment(); } @JsonIgnore public FieldSchema getFieldSchema() { return fieldSchema; } } |
data class | Data Class | t | f | t | 0 | 11479 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveTableWrapper.java/#L367-L396 | 1 | 1620 | 11479 | major | ||
| 5193 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 14519 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 5193 | 14519 | major | ||
| 637 | { "message": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | long method | t | t | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 1 | 637 | 6316 | minor | ||
| 2613 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 15043 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 2613 | 15043 | minor | ||
| 5744 | { "response": "YES, I found bad smells", "bad smells are": [ "Long method" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
long method | long method | t | t | t | 0 | 14137 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5744 | 14137 | minor | ||
| 2364 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | 1. data class | t | t | t | 0 | 14255 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 2364 | 14255 | minor | ||
| 2652 | return getCumulativeMemoryWithinPhase(join); YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method 2 Feature envy | t | f | t | 0 | 15177 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2652 | 15177 | major | ||
| 722 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method, data class | t | t | t | data class | 0 | 6833 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 722 | 6833 | minor | |
| 1200 | { "output": "YES I found bad smells", "bad smells are": "1. Long Method, 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 10279 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 1 | 1200 | 10279 | minor | |
| 2559 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14835 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2559 | 14835 | major | ||
| 1168 | {"output": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
long method | 1. long method | t | t | t | 0 | 10191 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 1 | 1168 | 10191 | minor | ||
| 2388 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean fetchNext() throws IgniteCheckedException { if (data == null) return false; try { if (!data.next()) { close(); return false; } if (res != null) { Value[] values = res.currentRow(); for (int c = 0; c < row.length; c++) { Value val = values[c]; if (val instanceof GridH2ValueCacheObject) { GridH2ValueCacheObject valCacheObj = (GridH2ValueCacheObject)values[c]; row[c] = valCacheObj.getObject(true); } else row[c] = val.getObject(); } } else { for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1); } return true; } catch (SQLException e) { throw new IgniteSQLException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14352 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/H2ResultSetIterator.java/#L101-L137 | 2 | 2388 | 14352 | minor | ||
| 1395 | YES I found bad smells the bad smells are: - Feature envy - Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
feature envy | - Feature envy- Long method | t | f | t | 0 | 10851 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 2 | 1395 | 10851 | minor | ||
| 791 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | long method | t | t | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 1 | 791 | 7535 | minor | ||
| 1299 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10640 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 2 | 1299 | 10640 | major | |
| 224 | { "response": "YES, I found bad smells", "the bad smells are": [ "1. Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processSelectedKeys() { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext();) { SelectionKey key = i.next(); i.remove(); final SelectableChannel sc = key.channel(); // do not attempt to read/write until handle is set (e.g. after handshake is completed) if (key.isReadable() && key.attachment() != null) { read(key); } else if (key.isWritable() && key.attachment() != null) { write(key); } else if (key.isAcceptable()) { assert sc == serverSocketChannel; accept(); } else if (key.isConnectable()) { finishConnect(key); } } } |
long method | 1. long method | t | t | t | 0 | 2418 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-ipc/src/main/java/org/apache/hyracks/ipc/impl/IPCConnectionManager.java/#L213-L230 | 2 | 224 | 2418 | minor | ||
| 2256 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AnElementElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.xtext.ui.tests.editor.contentassist.TwoContextsTestLanguage.AnElement"); private final Group cGroup = (Group)rule.eContents().get(1); private final Assignment cNameAssignment_0 = (Assignment)cGroup.eContents().get(0); private final RuleCall cNameIDTerminalRuleCall_0_0 = (RuleCall)cNameAssignment_0.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Keyword cRefersToKeyword_1_0 = (Keyword)cGroup_1.eContents().get(0); private final Assignment cReferredAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final CrossReference cReferredAnElementCrossReference_1_1_0 = (CrossReference)cReferredAssignment_1_1.eContents().get(0); private final RuleCall cReferredAnElementIDTerminalRuleCall_1_1_0_1 = (RuleCall)cReferredAnElementCrossReference_1_1_0.eContents().get(1); private final Keyword cSemicolonKeyword_2 = (Keyword)cGroup.eContents().get(2); //AnElement: // name=ID ('refersTo' referred=[AnElement])? ';'; @Override public ParserRule getRule() { return rule; } //name=ID ('refersTo' referred=[AnElement])? ';' public Group getGroup() { return cGroup; } //name=ID public Assignment getNameAssignment_0() { return cNameAssignment_0; } //ID public RuleCall getNameIDTerminalRuleCall_0_0() { return cNameIDTerminalRuleCall_0_0; } //('refersTo' referred=[AnElement])? public Group getGroup_1() { return cGroup_1; } //'refersTo' public Keyword getRefersToKeyword_1_0() { return cRefersToKeyword_1_0; } //referred=[AnElement] public Assignment getReferredAssignment_1_1() { return cReferredAssignment_1_1; } //[AnElement] public CrossReference getReferredAnElementCrossReference_1_1_0() { return cReferredAnElementCrossReference_1_1_0; } //ID public RuleCall getReferredAnElementIDTerminalRuleCall_1_1_0_1() { return cReferredAnElementIDTerminalRuleCall_1_1_0_1; } //';' public Keyword getSemicolonKeyword_2() { return cSemicolonKeyword_2; } } |
data class | data class | t | t | t | 0 | 13691 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/TwoContextsTestLanguageGrammarAccess.java/#L40-L82 | 1 | 2256 | 13691 | major | ||
| 1881 | {"response": "YES, I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | long method | t | t | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 1 | 1881 | 12286 | minor | ||
| 695 | YES, I found bad smells the bad smells are: 1.Long method 2. Feature envy 3. Repeating code 4. Code duplication 5. Insufficient commenting 6. Magic numbers 7. Primitive obsession 8. Inconsistent formatting 9. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method 2 Feature envy3 Repeating code4 Code duplication 5 Insufficient commenting 6 Magic numbers 7 Primitive obsession 8 Inconsistent formatting 9 Unused variables | t | f | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 695 | 6659 | major | ||
| 2228 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class TaskRemoval implements WorkerHistoryItem { private final String taskId; @JsonCreator public TaskRemoval( @JsonProperty("taskId") String taskId ) { this.taskId = taskId; } @JsonProperty public String getTaskId() { return taskId; } @Override public String toString() { return "TaskRemoval{" + "taskId='" + taskId + '\'' + '}'; } } |
data class | 1. data class | t | t | t | 0 | 13581 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/indexing-service/src/main/java/org/apache/druid/indexing/worker/WorkerHistoryItem.java/#L64-L89 | 1 | 2228 | 13581 | major | ||
| 2262 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 13720 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 2262 | 13720 | critical | ||
| 2525 | {"answer": "YES I found bad smells", "detected_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private public class MetricsAssignmentManagerSourceImpl extends BaseSourceImpl implements MetricsAssignmentManagerSource { private MutableGaugeLong ritGauge; private MutableGaugeLong ritCountOverThresholdGauge; private MutableGaugeLong ritOldestAgeGauge; private MetricHistogram ritDurationHisto; private MutableFastCounter operationCounter; private OperationMetrics assignMetrics; private OperationMetrics unassignMetrics; private OperationMetrics moveMetrics; private OperationMetrics reopenMetrics; private OperationMetrics openMetrics; private OperationMetrics closeMetrics; private OperationMetrics splitMetrics; private OperationMetrics mergeMetrics; public MetricsAssignmentManagerSourceImpl() { this(METRICS_NAME, METRICS_DESCRIPTION, METRICS_CONTEXT, METRICS_JMX_CONTEXT); } public MetricsAssignmentManagerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); } public void init() { ritGauge = metricsRegistry.newGauge(RIT_COUNT_NAME, RIT_COUNT_DESC, 0L); ritCountOverThresholdGauge = metricsRegistry.newGauge(RIT_COUNT_OVER_THRESHOLD_NAME, RIT_COUNT_OVER_THRESHOLD_DESC,0L); ritOldestAgeGauge = metricsRegistry.newGauge(RIT_OLDEST_AGE_NAME, RIT_OLDEST_AGE_DESC, 0L); ritDurationHisto = metricsRegistry.newTimeHistogram(RIT_DURATION_NAME, RIT_DURATION_DESC); operationCounter = metricsRegistry.getCounter(OPERATION_COUNT_NAME, 0L); /** * NOTE: Please refer to HBASE-9774 and HBASE-14282. Based on these two issues, HBase is * moving away from using Hadoop's metric2 to having independent HBase specific Metrics. Use * {@link BaseSourceImpl#registry} to register the new metrics. */ assignMetrics = new OperationMetrics(registry, ASSIGN_METRIC_PREFIX); unassignMetrics = new OperationMetrics(registry, UNASSIGN_METRIC_PREFIX); moveMetrics = new OperationMetrics(registry, MOVE_METRIC_PREFIX); reopenMetrics = new OperationMetrics(registry, REOPEN_METRIC_PREFIX); openMetrics = new OperationMetrics(registry, OPEN_METRIC_PREFIX); closeMetrics = new OperationMetrics(registry, CLOSE_METRIC_PREFIX); splitMetrics = new OperationMetrics(registry, SPLIT_METRIC_PREFIX); mergeMetrics = new OperationMetrics(registry, MERGE_METRIC_PREFIX); } @Override public void setRIT(final int ritCount) { ritGauge.set(ritCount); } @Override public void setRITCountOverThreshold(final int ritCount) { ritCountOverThresholdGauge.set(ritCount); } @Override public void setRITOldestAge(final long ritOldestAge) { ritOldestAgeGauge.set(ritOldestAge); } @Override public void incrementOperationCounter() { operationCounter.incr(); } @Override public void updateRitDuration(long duration) { ritDurationHisto.add(duration); } @Override public OperationMetrics getAssignMetrics() { return assignMetrics; } @Override public OperationMetrics getUnassignMetrics() { return unassignMetrics; } @Override public OperationMetrics getSplitMetrics() { return splitMetrics; } @Override public OperationMetrics getMergeMetrics() { return mergeMetrics; } @Override public OperationMetrics getMoveMetrics() { return moveMetrics; } @Override public OperationMetrics getReopenMetrics() { return reopenMetrics; } @Override public OperationMetrics getOpenMetrics() { return openMetrics; } @Override public OperationMetrics getCloseMetrics() { return closeMetrics; } } |
data class | data class | t | t | t | 0 | 14720 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-hadoop2-compat/src/main/java/org/apache/hadoop/hbase/master/MetricsAssignmentManagerSourceImpl.java/#L28-L146 | 1 | 2525 | 14720 | minor | ||
| 1234 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10369 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 1234 | 10369 | minor | ||
| 1161 | {"response": "YES, I found bad smells", "detected_bad_smells": ["1. Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
blob | 1. blob | t | t | t | 0 | 10165 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 1161 | 10165 | minor | ||
| 1538 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11226 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 1538 | 11226 | major | ||
| 2579 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | blob, data class | t | t | t | blob | 0 | 14944 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 1 | 2579 | 14944 | major | |
| 54 | {"response": "YES I found bad smells, the bad smells are: 3. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /*package*/ class WafFolderContent { private final WafFolder rootFolder; private final List subFolders; private final List files; /** * Creates instance of the folder content. * @param rootFolder root folder * @param subFolders sub folders * @param files files */ public WafFolderContent(WafFolder rootFolder, List subFolders, List files) { this.rootFolder = rootFolder; this.subFolders = subFolders; this.files = files; } /** * Gets root folder. * @return root folder */ public WafFolder getRootFolder() { return rootFolder; } /** * Gets sub folders. * @return sub folders */ public List getSubFolders() { return subFolders; } /** * Gets files. * @return files */ public List getFiles() { return files; } } |
data class | 3. data class | t | t | t | 0 | 953 | https://github.com/Esri/geoportal-server-harvester/blob/b8c69260e3d6ec10df6514c201219e690cfba048/geoportal-connectors/geoportal-harvester-waf/src/main/java/com/esri/geoportal/harvester/waf/WafFolderContent.java/#L23-L65 | 1 | 54 | 953 | major | ||
| 2059 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { @SerializedName("typ") public String type; @SerializedName("alg") public String algorithm; @SerializedName("cty") public String contentType; } |
data class | blob, data class | t | t | f | blob | data class | 0 | 12962 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/jwt/Header.java/#L23-L30 | 1 | 2059 | 12962 | major |
| 2632 | {"response": "YES I found bad smells", "bad smells are": ["1. Blob", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 15108 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 1 | 2632 | 15108 | major | |
| 1106 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9879 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 1106 | 9879 | major | ||
| 2164 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | long method | t | t | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 1 | 2164 | 13339 | minor | ||
| 2188 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
long method | long method, blob | t | t | t | blob | 0 | 13444 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 1 | 2188 | 13444 | minor | |
| 2631 | { "message": "YES I found bad smells", "detected_smells": [ "the bad smells are: 1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class InstantiatedVersionedLabel extends VersionedLabel implements InstantiatedVersionedComponent { private final String instanceId; private final String groupId; public InstantiatedVersionedLabel(final String instanceId, final String instanceGroupId) { this.instanceId = instanceId; this.groupId = instanceGroupId; } @Override public String getInstanceId() { return instanceId; } @Override public String getInstanceGroupId() { return groupId; } } |
data class | the bad smells are: 1. data class | t | t | t | 0 | 15100 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/registry/flow/mapping/InstantiatedVersionedLabel.java/#L22-L40 | 1 | 2631 | 15100 | major | ||
| 1435 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | long method | t | t | t | 0 | 10960 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 1 | 1435 | 10960 | major | ||
| 2589 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "setOrderAttributesResult", "responseMetadata" }) @XmlRootElement(name = "SetOrderAttributesResponse") public class SetOrderAttributesResponse { @XmlElement(name = "SetOrderAttributesResult", required = true) protected SetOrderAttributesResult setOrderAttributesResult; @XmlElement(name = "ResponseMetadata", required = true) protected ResponseMetadata responseMetadata; public SetOrderAttributesResponse() { super(); } public SetOrderAttributesResult getSetOrderAttributesResult() { return setOrderAttributesResult; } public ResponseMetadata getResponseMetadata() { return responseMetadata; } } |
data class | data class | t | t | t | 0 | 14996 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/model/SetOrderAttributesResponse.java/#L39-L65 | 1 | 2589 | 14996 | critical | ||
| 1318 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10692 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1318 | 10692 | major | ||
| 306 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final static class Builder { private Supplier initialValue; private UnaryOperator splitOperator = null; private BinaryOperator mergeOperator = null; private Builder() { } public Builder initialValue(final Supplier initialValue) { this.initialValue = initialValue; return this; } public Builder splitOperator(final UnaryOperator splitOperator) { this.splitOperator = splitOperator; return this; } public Builder mergeOperator(final BinaryOperator mergeOperator) { this.mergeOperator = mergeOperator; return this; } public SackStrategy create() { return new SackStrategy(this.initialValue, this.splitOperator, this.mergeOperator); } } |
data class | data class | t | t | t | 0 | 3195 | https://github.com/apache/tinkerpop/blob/7d9df0f0acf08f9e675ca7b337fc5e0243c09b53/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/SackStrategy.java/#L58-L85 | 1 | 306 | 3195 | major | ||
| 953 | {"message": "YES I found bad smells, the bad smells are:", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | long method | t | t | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 1 | 953 | 8529 | minor | ||
| 966 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void alterTableStatsForTruncate(RawStore ms, String catName, String dbName, String tableName, Table table, List partNames, String validWriteIds, long writeId) throws Exception { if (partNames == null) { if (0 != table.getPartitionKeysSize()) { for (Partition partition : ms.getPartitions(catName, dbName, tableName, Integer.MAX_VALUE)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } else { EnvironmentContext environmentContext = new EnvironmentContext(); updateStatsForTruncate(table.getParameters(), environmentContext); if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALTER_TABLE, new AlterTableEvent(table, table, true, true, writeId, this)); } // TODO: this should actually pass thru and set writeId for txn stats. if (writeId > 0) { table.setWriteId(writeId); } alterHandler.alterTable(ms, wh, catName, dbName, tableName, table, environmentContext, this, validWriteIds); } } else { for (Partition partition : ms.getPartitionsByNames(catName, dbName, tableName, partNames)) { alterPartitionForTruncate(ms, catName, dbName, tableName, table, partition, validWriteIds, writeId); } } return; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 8633 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java/#L2854-L2895 | 1 | 966 | 8633 | minor | |
| 2145 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | Feature envy | t | f | t | 0 | 13274 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 2 | 2145 | 13274 | minor | ||
| 781 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 781 | 7457 | major | ||
| 2153 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 2153 | 13295 | minor | ||
| 2299 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Duplicate code 4. Hardcoded values 5. Unused variables 6. Poor exception handling 7. Excessive commenting | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
long method | Long method2 Magic numbers3 Duplicate code4 Hardcoded values5 Unused variables6 Poor exception handling7 Excessive commenting | t | f | t | 0 | 14028 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 2299 | 14028 | major | ||
| 872 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
long method | long method, data class | t | t | t | data class | 0 | 7980 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 1 | 872 | 7980 | minor | |
| 2046 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void checkAlternativeConstructor() { // Local Declarations MasterDetailsPair mDetailsP; DataComponent dComponent; String MasterType1 = "TypeOne!"; // Setup DataComponent dComponent = new DataComponent(); dComponent.setName(MasterType1); IEntry entry = new StringEntry(); // Add entry to dComponent dComponent.addEntry(entry); // Call Alternative Constructor mDetailsP = new MasterDetailsPair(MasterType1, dComponent); // Check values. Should be typeone and equal to the declared // dataComponent assertEquals(MasterType1, mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // Try to pass null to the constructor - sets values appropriately mDetailsP = new MasterDetailsPair(null, dComponent); // null master assertNull(mDetailsP.getMaster()); assertTrue(dComponent.equals(mDetailsP.getDetails())); // DataComponent null mDetailsP = new MasterDetailsPair(MasterType1, null); assertEquals(MasterType1, mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); // Both null mDetailsP = new MasterDetailsPair(null, null); assertNull(mDetailsP.getMaster()); assertNull(mDetailsP.getDetails()); } |
long method | 1. long method | t | t | t | 0 | 12872 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MasterDetailsPairTester.java/#L201-L238 | 1 | 2046 | 12872 | minor | ||
| 1619 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | Long method2 Feature envy | t | f | t | 0 | 11477 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 2 | 1619 | 11477 | minor | ||
| 2326 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
long method | 1. long method | t | t | t | 0 | 14143 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 1 | 2326 | 14143 | minor | ||
| 1442 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Magic numbers 4. Duplicate code 5. Inconsistent naming conventions 6. Mixing of responsibilities 7. Nested if statements 8. Use of ternary operator 9. Redundant checks 10. Tight coupling between classes | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
feature envy | Long method2 Feature envy3 Magic numbers4 Duplicate code5 Inconsistent naming conventions6 Mixing of responsibilities7 Nested if statements8 Use of ternary operator9 Redundant checks | t | f | t | 0 | 10976 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 1442 | 10976 | minor | ||
| 1078 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 9647 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1078 | 9647 | minor | ||
| 1311 | {"result": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public ListenableFuture recover(QueueManagingVirtualHost virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map, Integer> queueRecoveries = new TreeMap<>(); Map> recoveredMessages = new HashMap<>(); Map> unusedMessages = new TreeMap<>(); Map unknownQueuesWithMessages = new HashMap<>(); Map, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry, Integer> entry : queueRecoveries.entrySet()) { Queue queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } |
long method | long method, data class | t | t | t | data class | 0 | 10681 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/virtualhost/SynchronousMessageStoreRecoverer.java/#L63-L151 | 1 | 1311 | 10681 | critical | |
| 2422 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | 1. long method | t | t | t | 0 | 14435 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 2422 | 14435 | minor | ||
| 1516 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static boolean typeCheckMethodsWithGenerics(ClassNode receiver, ClassNode[] arguments, MethodNode candidateMethod) { if (isUsingUncheckedGenerics(receiver)) { return true; } if (CLASS_Type.equals(receiver) && receiver.isUsingGenerics() && !candidateMethod.getDeclaringClass().equals(receiver) && !(candidateMethod instanceof ExtensionMethodNode)) { return typeCheckMethodsWithGenerics(receiver.getGenericsTypes()[0].getType(), arguments, candidateMethod); } // both candidate method and receiver have generic information so a check is possible GenericsType[] genericsTypes = candidateMethod.getGenericsTypes(); boolean methodUsesGenerics = (genericsTypes != null && genericsTypes.length > 0); boolean isExtensionMethod = candidateMethod instanceof ExtensionMethodNode; if (isExtensionMethod && methodUsesGenerics) { ClassNode[] dgmArgs = new ClassNode[arguments.length + 1]; dgmArgs[0] = receiver; System.arraycopy(arguments, 0, dgmArgs, 1, arguments.length); MethodNode extensionMethodNode = ((ExtensionMethodNode) candidateMethod).getExtensionMethodNode(); return typeCheckMethodsWithGenerics(extensionMethodNode.getDeclaringClass(), dgmArgs, extensionMethodNode, true); } else { return typeCheckMethodsWithGenerics(receiver, arguments, candidateMethod, false); } } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11165 | https://github.com/apache/groovy/blob/00ee0547c00673a93e0843a9d72c8e4293d1efdb/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java/#L1460-L1483 | 1 | 1516 | 11165 | minor | |
| 3396 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 3396 | 6591 | minor | ||
| 1230 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | 1. data class | t | t | t | 0 | 10362 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 1230 | 10362 | critical | ||
| 2447 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | data class, long method | t | t | t | data class | 0 | 14497 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 2447 | 14497 | minor | |
| 2583 | YES found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 14963 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2583 | 14963 | minor | ||
| 230 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method", "2. Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 2513 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 230 | 2513 | minor | |
| 1026 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 9361 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1026 | 9361 | minor | ||
| 324 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | data class, long method | t | t | t | long method | 0 | 3343 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 324 | 3343 | major | |
| 5325 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 14949 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 5325 | 14949 | major | ||
| 934 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 8390 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 2 | 934 | 8390 | minor | ||
| 1142 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override ValueNode preprocess(int numTables, FromList outerFromList, SubqueryList outerSubqueryList, PredicateList outerPredicateList) throws StandardException { /* Only preprocess this node once. We may get called multiple times * due to tree transformations. */ if (preprocessed) { return this; } preprocessed = true; boolean flattenable; ValueNode topNode = this; final boolean haveOrderBy; // need to remember for flattening decision // Push the order by list down to the ResultSet if (orderByList != null) { haveOrderBy = true; // If we have more than 1 ORDERBY columns, we may be able to // remove duplicate columns, e.g., "ORDER BY 1, 1, 2". if (orderByList.size() > 1) { orderByList.removeDupColumns(); } resultSet.pushOrderByList(orderByList); orderByList = null; } else { haveOrderBy = false; } resultSet = resultSet.preprocess(numTables, null, (FromList) null); if (leftOperand != null) { leftOperand = leftOperand.preprocess(numTables, outerFromList, outerSubqueryList, outerPredicateList); } // Eliminate any unnecessary DISTINCTs if (resultSet instanceof SelectNode) { if (((SelectNode) resultSet).hasDistinct()) { ((SelectNode) resultSet).clearDistinct(); /* We need to remember to check for single unique value * at execution time for expression subqueries. */ if (subqueryType == EXPRESSION_SUBQUERY) { distinctExpression = true; } } } /* Lame transformation - For IN/ANY subqueries, if * result set is guaranteed to return at most 1 row * and it is not correlated * then convert the subquery into the matching expression * subquery type. For example: * c1 in (select min(c1) from t2) * becomes: * c1 = (select min(c1) from t2) * (This actually showed up in an app that a potential customer * was porting from SQL Server.) * The transformed query can then be flattened if appropriate. */ if ((isIN() || isANY()) && resultSet.returnsAtMostOneRow()) { if (! hasCorrelatedCRs()) { changeToCorrespondingExpressionType(); } } /* NOTE: Flattening occurs before the pushing of * the predicate, since the pushing will add a node * above the SubqueryNode. */ /* Values subquery is flattenable if: * o It is not under an OR. * o It is not a subquery in a having clause (DERBY-3257) * o It is an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ flattenable = (resultSet instanceof RowResultSetNode) && underTopAndNode && !havingSubquery && !haveOrderBy && offset == null && fetchFirst == null && !isWhereExistsAnyInWithWhereSubquery() && parentComparisonOperator != null; if (flattenable) { /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ leftOperand = parentComparisonOperator.getLeftOperand(); // Flatten the subquery RowResultSetNode rrsn = (RowResultSetNode) resultSet; FromList fl = new FromList(getContextManager()); // Remove ourselves from the outer subquery list outerSubqueryList.removeElement(this); /* We only need to add the table from the subquery into * the outer from list if the subquery itself contains * another subquery. Otherwise, it just becomes a constant. */ if (rrsn.subquerys.size() != 0) { fl.addElement(rrsn); outerFromList.destructiveAppend(fl); } /* Append the subquery's subquery list to the * outer subquery list. */ outerSubqueryList.destructiveAppend(rrsn.subquerys); /* return the new join condition * If we are flattening an EXISTS then there is no new join * condition since there is no leftOperand. Simply return * TRUE. * * NOTE: The outer where clause, etc. has already been normalized, * so we simply return the BinaryComparisonOperatorNode above * the new join condition. */ return getNewJoinCondition(leftOperand, getRightOperand()); } /* Select subquery is flattenable if: * o It is not under an OR. * o The subquery type is IN, ANY or EXISTS or * an expression subquery on the right side * of a BinaryComparisonOperatorNode. * o There are no aggregates in the select list * o There is no group by clause or having clause. * o There is a uniqueness condition that ensures * that the flattening of the subquery will not * introduce duplicates into the result set. * o The subquery is not part of a having clause (DERBY-3257) * o There are no windows defined on it * * OR, * o The subquery is NOT EXISTS, NOT IN, ALL (beetle 5173). * o Either a) it does not appear within a WHERE clause, or * b) it appears within a WHERE clause but does not itself * contain a WHERE clause with other subqueries in it. * (DERBY-3301) */ boolean flattenableNotExists = (isNOT_EXISTS() || canAllBeFlattened()); flattenable = (resultSet instanceof SelectNode) && !((SelectNode)resultSet).hasWindows() && !haveOrderBy && offset == null && fetchFirst == null && underTopAndNode && !havingSubquery && !isWhereExistsAnyInWithWhereSubquery() && (isIN() || isANY() || isEXISTS() || flattenableNotExists || parentComparisonOperator != null); if (flattenable) { SelectNode select = (SelectNode) resultSet; if ((!select.hasAggregatesInSelectList()) && (select.havingClause == null)) { ValueNode origLeftOperand = leftOperand; /* Check for uniqueness condition. */ /* Is the column being returned by the subquery * a candidate for an = condition? */ boolean additionalEQ = (subqueryType == IN_SUBQUERY) || (subqueryType == EQ_ANY_SUBQUERY); additionalEQ = additionalEQ && ((leftOperand instanceof ConstantNode) || (leftOperand instanceof ColumnReference) || (leftOperand.requiresTypeFromContext())); /* If we got this far and we are an expression subquery * then we want to set leftOperand to be the left side * of the comparison in case we pull the comparison into * the flattened subquery. */ if (parentComparisonOperator != null) { leftOperand = parentComparisonOperator.getLeftOperand(); } /* Never flatten to normal join for NOT EXISTS. */ if ((! flattenableNotExists) && select.uniqueSubquery(additionalEQ)) { // Flatten the subquery return flattenToNormalJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList); } /* We can flatten into an EXISTS join if all of the above * conditions except for a uniqueness condition are true * and: * o Subquery only has a single entry in its from list * and that entry is a FromBaseTable * o All predicates in the subquery's where clause are * pushable. * o The leftOperand, if non-null, is pushable. * If the subquery meets these conditions then we will flatten * the FBT into an EXISTS FBT, pushd the subquery's * predicates down to the PRN above the EBT and * mark the predicates to say that they cannot be pulled * above the PRN. (The only way that we can guarantee correctness * is if the predicates do not get pulled up. If they get pulled * up then the single next logic for an EXISTS join does not work * because that row may get disqualified at a higher level.) * DERBY-4001: Extra conditions to allow flattening to a NOT * EXISTS join (in a NOT EXISTS join it does matter on which * side of the join predicates/restrictions are applied): * o All the predicates must reference the FBT, otherwise * predicates meant for the right side of the join may be * applied to the left side of the join. * o The right operand (in ALL and NOT IN) must reference the * FBT, otherwise the generated join condition may be used * to restrict the left side of the join. */ else if ( (isIN() || isANY() || isEXISTS() || flattenableNotExists) && ((leftOperand == null) ? true : leftOperand.categorize(new JBitSet(numTables), false)) && select.getWherePredicates().allPushable()) { FromBaseTable fbt = singleFromBaseTable(select.getFromList()); if (fbt != null && (!flattenableNotExists || (select.getWherePredicates().allReference(fbt) && rightOperandFlattenableToNotExists(numTables, fbt)))) { return flattenToExistsJoin(numTables, outerFromList, outerSubqueryList, outerPredicateList, flattenableNotExists); } } // restore leftOperand to its original value leftOperand = origLeftOperand; } } resultSet.pushQueryExpressionSuffix(); resultSet.pushOffsetFetchFirst( offset, fetchFirst, hasJDBClimitClause ); /* We transform the leftOperand and the select list for quantified * predicates that have a leftOperand into a new predicate and push it * down to the subquery after we preprocess the subquery's resultSet. * We must do this after preprocessing the underlying subquery so that * we know where to attach the new predicate. * NOTE - If we pushed the predicate before preprocessing the underlying * subquery, then the point of attachment would depend on the form of * that subquery. (Where clause? Having clause?) */ if (leftOperand != null) { topNode = pushNewPredicate(numTables); pushedNewPredicate = true; } /* EXISTS and NOT EXISTS subqueries that haven't been flattened, need * an IS [NOT] NULL node on top so that they return a BOOLEAN. Other * cases are taken care of in pushNewPredicate. */ else if (isEXISTS() || isNOT_EXISTS()) { topNode = genIsNullTree(isEXISTS()); subqueryType = EXISTS_SUBQUERY; } /* ** Do inVariant and correlated checks now. We ** aren't going to use the results here, but they ** have been stashed away by isInvariant() and hasCorrelatedCRs() */ isInvariant(); hasCorrelatedCRs(); /* If parentComparisonOperator is non-null then we are an * expression subquery that was considered to be a candidate * for flattening, but we didn't get flattened. In that case * we are the rightOperand of the parent. We need to update * the parent's rightOperand with the new topNode and return * the parent because the parent is letting us decide whether * or not to replace the entire comparison, which we can do * if we flatten. Otherwise we simply return the new top node. */ if (parentComparisonOperator != null) { parentComparisonOperator.setRightOperand(topNode); return parentComparisonOperator; } return topNode; } |
long method | long method | t | t | t | 0 | 10095 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/SubqueryNode.java/#L606-L926 | 1 | 1142 | 10095 | critical | ||
| 1419 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10925 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1419 | 10925 | minor | ||
| 1053 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy: next(), interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters 3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. 1 and 0) without any explanation or clear purpose, making it difficult to understand 6. Lack of comments: there are no comments in the code explaining the purpose or logic behind certain decisions or methods, making it difficult for future developers to understand 7. Poor naming conventions: variable names such as "next" and "method" are not descriptive enough, making it difficult to understand their purpose and usage | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Invocation next() { if (interceptors.hasNext()) { final Interceptor interceptor = interceptors.next(); final Object nextInstance = interceptor.getInstance(); final Method nextMethod = interceptor.getMethod(); if (nextMethod.getParameterTypes().length == 1 && nextMethod.getParameterTypes()[0] == InvocationContext.class) { return new InterceptorInvocation(nextInstance, nextMethod, this); } else { return new LifecycleInvocation(nextInstance, nextMethod, this, parameters); } } else if (method != null) { //EJB 3.1, it is allowed that timeout method does not have parameter Timer.class, //However, while invoking the timeout method, the timer value is passed, as it is also required by InnvocationContext.getTimer() method final Object[] methodParameters; if (operation.equals(Operation.TIMEOUT) && method.getParameterTypes().length == 0) { methodParameters = new Object[0]; } else { methodParameters = parameters; } return new BeanInvocation(target, method, methodParameters); } else { return new NoOpInvocation(); } } |
long method | Long method2 Feature envy: next(), interceptors, interceptorgetInstance(), interceptorgetMethod(), LifecycleInvocation, InterceptorInvocation, operationequals(), methodgetParameterTypes(), InvocationContextgetTimer(), BeanInvocation, target, method, methodParameters, parameters3 Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4 Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5 Magic numbers: the code contains integer values (eg | t | f | t | interceptors, interceptor.getInstance(), interceptor.getMethod(), LifecycleInvocation, InterceptorInvocation, operation.equals(), method.getParameterTypes(), InvocationContext.getTimer(), BeanInvocation, target, method, methodParameters, parameters3. Cognitive complexity: multiple conditional statements and nested if statements make the code difficult to understand and reason about 4. Mixing of business logic and method implementation: the code is performing both business logic and method implementation, making it less cohesive 5. Magic numbers: the code contains integer values (e.g. | 0 | 9480 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-core/src/main/java/org/apache/openejb/core/interceptor/ReflectionInvocationContext.java/#L153-L177 | 2 | 1053 | 9480 | minor | |
| 985 | {"output": "YES I found bad smells\n the bad smells are:\n 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | \n 1. data class | t | t | t | 0 | 8878 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 985 | 8878 | major | ||
| 1454 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, data class | t | t | t | data class | 0 | 11007 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 1454 | 11007 | minor | |
| 2683 | */ YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
long method | Long method2 Feature envy | t | f | t | 0 | 15269 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 2683 | 15269 | minor | ||
| 1341 | {"output": "YES I found bad smells, the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
data class | 1. data class | t | t | t | 0 | 10742 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 1341 | 10742 | major | ||
| 2381 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2381 | 14338 | minor | ||
| 3987 | YES I found bad smells the bad smells are: 1. Long method 2. Unnecessary use of try-catch-finally block for exception handling 3. Use of generic exceptions instead of specific ones 4. Lack of modularization or abstraction in the code 5. Use of primitive data types instead of classes for handling requests and responses 6. Inconsistent use of method parameters (e.g. handler vs. requests) 7. Mixing of different responsibilities within the method (e.g. transaction handling, error handling, request processing) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
long method | Long method2 Unnecessary use of try-catch-finally block for exception handling3 Use of generic exceptions instead of specific ones4 Lack of modularization or abstraction in the code5 Use of primitive data types instead of classes for handling requests and responses6 Inconsistent use of method parameters (eg handler vs requests)7 Mixing of different responsibilities within the method (eg transaction handling, error handling, request processing) | t | f | t | error handling, request processing) | 0 | 10502 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 2 | 3987 | 10502 | minor | |
| 2626 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 15080 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 1 | 2626 | 15080 | minor | ||
| 659 | YES I found bad smells the bad smells are: 1. Long Constructor 2. Data class 3. Feature envy: the createJobMasterService method uses more variables from the constructor instead of its own parameters. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } } |
data class | Long Constructor2 Data class3 Feature envy: the createJobMasterService method uses more variables from the constructor instead of its own parameters | t | f | t | 0 | 6424 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 | 2 | 659 | 6424 | major | ||
| 1114 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public final Description matchClass(ClassTree classTree, VisitorState state) { if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) { return Description.NO_MATCH; } List ctors = ASTHelpers.getConstructors(classTree); List ctorsWithInject = ctors.stream() .filter(c -> hasInjectAnnotation().matches(c, state)) .collect(toImmutableList()); if (ctorsWithInject.size() != 1) { // Injection frameworks don't support multiple @Inject ctors. // There is already an ERROR check for it. // http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor return Description.NO_MATCH; } // collect the assignments in ctor Set variablesAssigned = new HashSet<>(); new TreeScanner() { @Override public Void visitAssignment(AssignmentTree tree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(tree.getVariable()); // check if it is instance field. if (symbol != null && symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()) { variablesAssigned.add(symbol); } return super.visitAssignment(tree, null); } }.scan((JCTree) getOnlyElement(ctorsWithInject), null); SuggestedFix.Builder fix = SuggestedFix.builder(); VariableTree variableTreeFirstMatch = null; for (Tree member : classTree.getMembers()) { if (!(member instanceof VariableTree)) { continue; } VariableTree variableTree = (VariableTree) member; if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) { continue; } if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) { continue; } variableTreeFirstMatch = variableTree; removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge); } if (variableTreeFirstMatch == null) { return Description.NO_MATCH; } if (fix.isEmpty()) { return describeMatch(variableTreeFirstMatch); } return describeMatch(variableTreeFirstMatch, fix.build()); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9896 | https://github.com/google/error-prone/blob/61cb540c08ec63faa56dccce00049cff1f8b41ea/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java/#L72-L128 | 2 | 1114 | 9896 | minor | ||
| 507 | YES I found bad smells The bad smells are: 1.Long method 2.Magic strings 3.Coupled design 4.Incomplete error handling 5.Condition redundancy 6.Poorly named variable and method names 7.Inadequate commenting/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void registerProjectsToFileBasedWorkspace(Iterable projectURIs, FileBasedWorkspace workspace) throws N4JSCompileException { // TODO GH-783 refactor FileBasedWorkspace, https://github.com/eclipse/n4js/issues/783 // this is reverse mapping of the one that is kept in the workspace Map registeredProjects = new HashMap<>(); workspace.getAllProjectLocationsIterator().forEachRemaining(uri -> { String projectName = workspace.getProjectDescription(uri).getProjectName(); registeredProjects.put(projectName, URIUtils.normalize(uri)); }); // register all projects with the file based workspace. for (URI uri : projectURIs) { URI projectURI = URIUtils.normalize(uri); final ProjectDescription projectDescription = projectDescriptionLoader .loadProjectDescriptionAtLocation(projectURI); if (projectDescription == null) { throw new N4JSCompileException( "Cannot load project description for project at " + projectURI.toFileString() + ". Make sure the project contains a valid package.json file."); } final String projectName = projectDescription.getProjectName(); if (skipRegistering(projectName, projectURI, registeredProjects)) { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Skipping already registered project '" + projectURI + "'"); } /* * We could call FileBasedWorkspace.registerProject which would fail silently. Still to avoid potential * side effects and to keep {@code registeredProjects} management simpler,we will skip it explicitly. */ continue; } try { if (logger != null && logger.isCreateDebugOutput()) { logger.debug("Registering project '" + projectURI + "'"); } workspace.registerProject(projectURI); registeredProjects.put(projectName, projectURI); } catch (N4JSBrokenProjectException e) { throw new N4JSCompileException("Unable to register project '" + projectURI + "'", e); } } } |
long method | Long method2Magic strings3Coupled design4Incomplete error handling5Condition redundancy6Poorly named variable and method names7Inadequate commenting/documentation | t | f | t | 0 | 5156 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/HeadlessHelper.java/#L82-L129 | 2 | 507 | 5156 | minor | ||
| 5299 | { "input_code": "public class Example { public void foo() { System.out.println(\"Hello, World!\"); } }", "common_code_smells": ["Blob", "Data Class", "Feature Envy", "Long Method"], "detected_bad_smells": { "blob": false, "data_class": false, "feature_envy": false, "long_method": true } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
blob | blob: false, data_class: false, feature_envy: false, long_method: true | t | t | t | data_class: false, feature_envy: false, long_method: true | 0 | 14830 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/airavata-api/airavata-api-stubs/src/main/java/org/apache/airavata/api/Airavata.java/#L33809-L33879 | 1 | 5299 | 14830 | major | |
| 2274 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 2274 | 13771 | major | |
| 328 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Blob", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Config { public String mysqlAddr; public Integer mysqlPort; public String mysqlUsername; public String mysqlPassword; public String mqNamesrvAddr; public String mqTopic; public String startType = "DEFAULT"; public String binlogFilename; public Long nextPosition; public Integer maxTransactionRows = 100; public void load() throws IOException { InputStream in = Config.class.getClassLoader().getResourceAsStream("rocketmq_mysql.conf"); Properties properties = new Properties(); properties.load(in); properties2Object(properties, this); } private void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } public void setMysqlAddr(String mysqlAddr) { this.mysqlAddr = mysqlAddr; } public void setMysqlPort(Integer mysqlPort) { this.mysqlPort = mysqlPort; } public void setMysqlUsername(String mysqlUsername) { this.mysqlUsername = mysqlUsername; } public void setMysqlPassword(String mysqlPassword) { this.mysqlPassword = mysqlPassword; } public void setBinlogFilename(String binlogFilename) { this.binlogFilename = binlogFilename; } public void setNextPosition(Long nextPosition) { this.nextPosition = nextPosition; } public void setMaxTransactionRows(Integer maxTransactionRows) { this.maxTransactionRows = maxTransactionRows; } public void setMqNamesrvAddr(String mqNamesrvAddr) { this.mqNamesrvAddr = mqNamesrvAddr; } public void setMqTopic(String mqTopic) { this.mqTopic = mqTopic; } public void setStartType(String startType) { this.startType = startType; } } |
data class | 1. blob, 2. data class | t | t | f | 1. blob | data class | 0 | 3385 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-mysql/src/main/java/org/apache/rocketmq/mysql/Config.java/#L26-L130 | 1 | 328 | 3385 | minor |
| 659 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultJobMasterServiceFactory implements JobMasterServiceFactory { private final JobMasterConfiguration jobMasterConfiguration; private final SlotPoolFactory slotPoolFactory; private final SchedulerFactory schedulerFactory; private final RpcService rpcService; private final HighAvailabilityServices haServices; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; public DefaultJobMasterServiceFactory( JobMasterConfiguration jobMasterConfiguration, SlotPoolFactory slotPoolFactory, SchedulerFactory schedulerFactory, RpcService rpcService, HighAvailabilityServices haServices, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) { this.jobMasterConfiguration = jobMasterConfiguration; this.slotPoolFactory = slotPoolFactory; this.schedulerFactory = schedulerFactory; this.rpcService = rpcService; this.haServices = haServices; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; } @Override public JobMaster createJobMasterService(JobGraph jobGraph, OnCompletionActions jobCompletionActions, ClassLoader userCodeClassloader) throws Exception { return new JobMaster( rpcService, jobMasterConfiguration, ResourceID.generate(), jobGraph, haServices, slotPoolFactory, schedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, jobCompletionActions, fatalErrorHandler, userCodeClassloader); } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 6424 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java/#L37-L95 | 1 | 659 | 6424 | major | |
| 1733 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
feature envy | Long Method, Feature Envy | t | f | t | Long Method | 0 | 11822 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1733 | 11822 | major | |
| 321 | { "output": "YES I found bad smells the bad smells are: 1. Long method, 2. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static final class DemoControls extends CustomControls implements ActionListener, ChangeListener { TransformAnim demo; JSlider shapeSlider, stringSlider, imageSlider; Font font = new Font(Font.SERIF, Font.BOLD, 10); JToolBar toolbar; ButtonBorder buttonBorder = new ButtonBorder(); @SuppressWarnings("LeakingThisInConstructor") public DemoControls(TransformAnim demo) { super(demo.name); this.demo = demo; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(Box.createVerticalStrut(5)); JToolBar bar = new JToolBar(SwingConstants.VERTICAL); bar.setFloatable(false); shapeSlider = new JSlider(SwingConstants.HORIZONTAL,0,20,demo.numShapes); shapeSlider.addChangeListener(this); TitledBorder tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numShapes) + " Shapes"); shapeSlider.setBorder(tb); shapeSlider.setOpaque(true); shapeSlider.setPreferredSize(new Dimension(80,44)); bar.add(shapeSlider); bar.addSeparator(); stringSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numStrings); stringSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numStrings) + " Strings"); stringSlider.setBorder(tb); stringSlider.setOpaque(true); stringSlider.setPreferredSize(new Dimension(80,44)); bar.add(stringSlider); bar.addSeparator(); imageSlider = new JSlider(SwingConstants.HORIZONTAL,0,10,demo.numImages); imageSlider.addChangeListener(this); tb = new TitledBorder(new EtchedBorder()); tb.setTitleFont(font); tb.setTitle(String.valueOf(demo.numImages) + " Images"); imageSlider.setBorder(tb); imageSlider.setOpaque(true); imageSlider.setPreferredSize(new Dimension(80,44)); bar.add(imageSlider); bar.addSeparator(); add(bar); toolbar = new JToolBar(); toolbar.setFloatable(false); addButton("T", "translate", demo.doTranslate); addButton("R", "rotate", demo.doRotate); addButton("SC", "scale", demo.doScale); addButton("SH", "shear", demo.doShear); add(toolbar); } public void addButton(String s, String tt, boolean state) { JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(s)); b.setFont(font); b.setSelected(state); b.setToolTipText(tt); b.setFocusPainted(false); b.setBorder(buttonBorder); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { JToggleButton b = (JToggleButton) e.getSource(); if (b.getText().equals("T")) { demo.doTranslate = b.isSelected(); } else if (b.getText().equals("R")) { demo.doRotate = b.isSelected(); } else if (b.getText().equals("SC")) { demo.doScale = b.isSelected(); } else if (b.getText().equals("SH")) { demo.doShear = b.isSelected(); } if (!demo.animating.running()) { demo.repaint(); } } @Override public void stateChanged(ChangeEvent e) { JSlider slider = (JSlider) e.getSource(); int value = slider.getValue(); TitledBorder tb = (TitledBorder) slider.getBorder(); if (slider.equals(shapeSlider)) { tb.setTitle(String.valueOf(value) + " Shapes"); demo.setShapes(value); } else if (slider.equals(stringSlider)) { tb.setTitle(String.valueOf(value) + " Strings"); demo.setStrings(value); } else if (slider.equals(imageSlider)) { tb.setTitle(String.valueOf(value) + " Images"); demo.setImages(value); } if (!demo.animating.running()) { demo.repaint(); } slider.repaint(); } @Override public Dimension getPreferredSize() { return new Dimension(80,38); } @Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { Thread me = Thread.currentThread(); while (thread == me) { for (int i = 1; i < toolbar.getComponentCount(); i++) { try { Thread.sleep(4444); } catch (InterruptedException e) { return; } ((AbstractButton) toolbar.getComponentAtIndex(i)).doClick(); } } thread = null; } } // End DemoControls |
blob | 1. long method, 2. blob | t | t | t | 1. long method | 0 | 3298 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/demo/share/jfc/J2Ddemo/java2d/demos/Transforms/TransformAnim.java/#L386-L518 | 1 | 321 | 3298 | major | |
| 1246 | YES I found bad smells. the bad smells are: 1.Long method 3.Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method3Magic numbers | t | f | t | 0 | 10421 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1246 | 10421 | minor | ||
| 1963 | YES I found bad smells the bad smells are: 1. Feature envy: The method uses multiple attributes and methods from the baseRequest object, indicating a potential violation of the single responsibility principle. 2. Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain. 3. Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code. 4. Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance. 5. Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain. 6. Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle. 7. Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public AsyncContextEvent(Context context,AsyncContextState asyncContext, HttpChannelState state, Request baseRequest, ServletRequest request, ServletResponse response) { super(null,request,response,null); _context=context; _asyncContext=asyncContext; _state=state; // If we haven't been async dispatched before if (baseRequest.getAttribute(AsyncContext.ASYNC_REQUEST_URI)==null) { // We are setting these attributes during startAsync, when the spec implies that // they are only available after a call to AsyncContext.dispatch(...); // have we been forwarded before? String uri=(String)baseRequest.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI); if (uri!=null) { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,uri); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH)); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getAttribute(RequestDispatcher.FORWARD_PATH_INFO)); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING)); } else { baseRequest.setAttribute(AsyncContext.ASYNC_REQUEST_URI,baseRequest.getRequestURI()); baseRequest.setAttribute(AsyncContext.ASYNC_CONTEXT_PATH,baseRequest.getContextPath()); baseRequest.setAttribute(AsyncContext.ASYNC_SERVLET_PATH,baseRequest.getServletPath()); baseRequest.setAttribute(AsyncContext.ASYNC_PATH_INFO,baseRequest.getPathInfo()); baseRequest.setAttribute(AsyncContext.ASYNC_QUERY_STRING,baseRequest.getQueryString()); } } } |
feature envy | Feature envy: The method uses multiple attributes and methods from the baseRequest object, indicating a potential violation of the single responsibility principle2 Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain3 Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code4 Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance5 Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain6 Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle7 Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code | t | f | t | indicating a potential violation of the single responsibility principle.2. Long method: The method is long, spanning over multiple lines and performing multiple tasks, indicating that it may be difficult to read, understand, and maintain.3. Shotgun surgery: Changing one aspect of the baseRequest object would require changes to this method, indicating a highly coupled code.4. Magic numbers/string literals: The method uses string literals like "FORWARD_REQUEST_URI" and "ASYNC_REQUEST_URI" to set and get attributes, making it difficult to understand their significance.5. Inconsistent formatting: The placement of brackets and white spaces is inconsistent, making the code difficult to read and maintain.6. Code duplication: The code to set the attributes for "uri" and without "uri" is essentially the same, indicating a violation of the DRY (Don't Repeat Yourself) principle.7. Non-descriptive variable names: The variable names like "baseRequest" and "state" do not convey their purpose, making it difficult to understand the code. | 0 | 12587 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContextEvent.java/#L42-L74 | 2 | 1963 | 12587 | minor | |
| 2233 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1762 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1762() {} public Customer1762(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1762[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 13595 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1762.java/#L8-L27 | 1 | 2233 | 13595 | minor | ||
| 1808 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 12049 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 1 | 1808 | 12049 | minor | |
| 2404 | {"response": "YES I found bad smells the bad smells are: Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method | t | t | t | 0 | 14385 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 2404 | 14385 | major | ||
| 996 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 1 | 996 | 9119 | minor | |
| 1688 | { "YES I found bad smells": "YES I found bad smells", "the bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11692 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 1688 | 11692 | minor | |
| 289 | { "message": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | 1. data class | t | t | t | 0 | 3068 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 1 | 289 | 3068 | major | ||
| 3396 | { "output": "YES I found bad smells the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | 1. long method | t | t | t | 0 | 6591 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 1 | 3396 | 6591 | minor | ||
| 935 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | Long method2 Feature envy | t | f | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 2 | 935 | 8393 | minor | ||
| 484 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | long method | t | t | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 1 | 484 | 4743 | minor | ||
| 5166 | :Parse the thrift exception and identify if exception belongs to workspace project or else Args: isAiravataException (bool) An object handle Returns: string YES I found bad smells the bad smells are: 1. Duplicated code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | Duplicated code2 Long method3 Feature envy | t | f | t | 0 | 14457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 2 | 5166 | 14457 | major | ||
| 1430 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Lack of cohesion 5. Poor exception handling 6. Nested try-catch blocks 7. Inappropriate use of if-else statements 8. Poor naming conventions (e.g. methodName, meth) 9. Too many parameters in method's signature 10. Coupled code (e.g. accessing methods and fields from other classes without proper encapsulation) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Object invoke(String methodName, Object returnValueIfNonExistent, Class[] paramTypes, Object[] params) throws DocletInvokeException { Method meth; try { meth = docletClass.getMethod(methodName, paramTypes); } catch (NoSuchMethodException exc) { if (returnValueIfNonExistent == null) { messager.error(Messager.NOPOS, "main.doclet_method_not_found", docletClassName, methodName); throw new DocletInvokeException(); } else { return returnValueIfNonExistent; } } catch (SecurityException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } if (!Modifier.isStatic(meth.getModifiers())) { messager.error(Messager.NOPOS, "main.doclet_method_must_be_static", docletClassName, methodName); throw new DocletInvokeException(); } ClassLoader savedCCL = Thread.currentThread().getContextClassLoader(); try { if (appClassLoader != null) // will be null if doclet class provided via API Thread.currentThread().setContextClassLoader(appClassLoader); return meth.invoke(null , params); } catch (IllegalArgumentException | NullPointerException exc) { messager.error(Messager.NOPOS, "main.internal_error_exception_thrown", docletClassName, methodName, exc.toString()); throw new DocletInvokeException(); } catch (IllegalAccessException exc) { messager.error(Messager.NOPOS, "main.doclet_method_not_accessible", docletClassName, methodName); throw new DocletInvokeException(); } catch (InvocationTargetException exc) { Throwable err = exc.getTargetException(); if (apiMode) throw new ClientCodeException(err); if (err instanceof java.lang.OutOfMemoryError) { messager.error(Messager.NOPOS, "main.out.of.memory"); } else { messager.error(Messager.NOPOS, "main.exception_thrown", docletClassName, methodName, exc.toString()); exc.getTargetException().printStackTrace(System.err); } throw new DocletInvokeException(); } finally { Thread.currentThread().setContextClassLoader(savedCCL); } } |
long method | Long method2 Feature envy3 Duplicate code4 Lack of cohesion5 Poor exception handling6 Nested try-catch blocks7 Inappropriate use of if-else statements8 Poor naming conventions (eg methodName, meth)9 Too many parameters in method's signature | t | f | t | meth)9. Too many parameters in method's signature | 0 | 10952 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/DocletInvoker.java/#L303-L357 | 2 | 1430 | 10952 | major | |
| 923 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 8280 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 2 | 923 | 8280 | minor | ||
| 1851 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy: multiple methods operate on the same instance variables 3. Primitive obsession: use of multiple boolean variables to represent different types 4. Message chain: method chaining in multiple places 5. Data class: class contains no behavior and just stores data 6. Duplicated code: similar logic repeated in multiple methods 7. Lack of encapsulation: direct access to all instance variables from outside the class 8. Switch statements instead of polymorphism: if/else statements used to handle different types instead of creating subclasses 9. Lack of abstraction: many specific boolean variables used instead of a single abstracted class 10. Comments used instead of meaningful method names: non-descriptive method names with comments explaining functionality instead 11. Unnecessary constructor parameters: excessive parameters in constructor that are not used in the class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | Long method2 Feature envy: multiple methods operate on the same instance variables 3 Primitive obsession: use of multiple boolean variables to represent different types 4 Message chain: method chaining in multiple places 5 Data class: class contains no behavior and just stores data 6 Duplicated code: similar logic repeated in multiple methods 7 Lack of encapsulation: direct access to all instance variables from outside the class 8 Switch statements instead of polymorphism: if/else statements used to handle different types instead of creating subclasses 9 Lack of abstraction: many specific boolean variables used instead of a single abstracted class | t | f | t | 0 | 12190 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 2 | 1851 | 12190 | minor | ||
| 1524 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ private String project; /** * The Team Project ID. Required if Project is not set. */ private UUID projectId; /** * The Team Id or name. Ignored if TeamId is set. */ private String team; /** * The Team Id */ private UUID teamId; /** * The team project Id or name. Ignored if ProjectId is set. */ public String getProject() { return project; } /** * The team project Id or name. Ignored if ProjectId is set. */ public void setProject(final String project) { this.project = project; } /** * The Team Project ID. Required if Project is not set. */ public UUID getProjectId() { return projectId; } /** * The Team Project ID. Required if Project is not set. */ public void setProjectId(final UUID projectId) { this.projectId = projectId; } /** * The Team Id or name. Ignored if TeamId is set. */ public String getTeam() { return team; } /** * The Team Id or name. Ignored if TeamId is set. */ public void setTeam(final String team) { this.team = team; } /** * The Team Id */ public UUID getTeamId() { return teamId; } /** * The Team Id */ public void setTeamId(final UUID teamId) { this.teamId = teamId; } } |
data class | Data Class | t | f | t | 0 | 11182 | https://github.com/Microsoft/vso-httpclient-java/blob/7b6329238498d7ad1934243150f955bea594df37/Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/types/TeamContext.java/#L24-L98 | 1 | 1524 | 11182 | major | ||
| 376 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override int recursionUnsafeHashCode() { return System.identityHashCode(this); } |
feature envy | Feature envy | t | f | t | 0 | 3877 | https://github.com/google/closure-compiler/blob/0393c80ca01b6b861376dad7f91043a38bb37dc0/src/com/google/javascript/rhino/jstype/AllType.java/#L112-L115 | 2 | 376 | 3877 | major | ||
| 1830 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 2 | 1830 | 12121 | critical | ||
| 97 | {"message": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Undertow { /** * Maximum size of the HTTP post content. When the value is -1, the default, the * size is unlimited. */ private DataSize maxHttpPostSize = DataSize.ofBytes(-1); /** * Size of each buffer. The default is derived from the maximum amount of memory * that is available to the JVM. */ private DataSize bufferSize; /** * Number of I/O threads to create for the worker. The default is derived from the * number of available processors. */ private Integer ioThreads; /** * Number of worker threads. The default is 8 times the number of I/O threads. */ private Integer workerThreads; /** * Whether to allocate buffers outside the Java heap. The default is derived from * the maximum amount of memory that is available to the JVM. */ private Boolean directBuffers; /** * Whether servlet filters should be initialized on startup. */ private boolean eagerFilterInit = true; private final Accesslog accesslog = new Accesslog(); public DataSize getMaxHttpPostSize() { return this.maxHttpPostSize; } public void setMaxHttpPostSize(DataSize maxHttpPostSize) { this.maxHttpPostSize = maxHttpPostSize; } public DataSize getBufferSize() { return this.bufferSize; } public void setBufferSize(DataSize bufferSize) { this.bufferSize = bufferSize; } public Integer getIoThreads() { return this.ioThreads; } public void setIoThreads(Integer ioThreads) { this.ioThreads = ioThreads; } public Integer getWorkerThreads() { return this.workerThreads; } public void setWorkerThreads(Integer workerThreads) { this.workerThreads = workerThreads; } public Boolean getDirectBuffers() { return this.directBuffers; } public void setDirectBuffers(Boolean directBuffers) { this.directBuffers = directBuffers; } public boolean isEagerFilterInit() { return this.eagerFilterInit; } public void setEagerFilterInit(boolean eagerFilterInit) { this.eagerFilterInit = eagerFilterInit; } public Accesslog getAccesslog() { return this.accesslog; } /** * Undertow access log properties. */ public static class Accesslog { /** * Whether to enable the access log. */ private boolean enabled = false; /** * Format pattern for access logs. */ private String pattern = "common"; /** * Log file name prefix. */ protected String prefix = "access_log."; /** * Log file name suffix. */ private String suffix = "log"; /** * Undertow access log directory. */ private File dir = new File("logs"); /** * Whether to enable access log rotation. */ private boolean rotate = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public File getDir() { return this.dir; } public void setDir(File dir) { this.dir = dir; } public boolean isRotate() { return this.rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } } } |
data class | blob, data class | t | t | t | blob | 0 | 1279 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java/#L949-L1124 | 1 | 97 | 1279 | major | |
| 2673 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Long method2 Feature envy | t | f | t | 0 | 15225 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 2 | 2673 | 15225 | major | ||
| 251 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Internal public final class ShortSerializer extends TypeSerializerSingleton { private static final long serialVersionUID = 1L; /** Sharable instance of the ShortSerializer. */ public static final ShortSerializer INSTANCE = new ShortSerializer(); private static final Short ZERO = (short) 0; @Override public boolean isImmutableType() { return true; } @Override public Short createInstance() { return ZERO; } @Override public Short copy(Short from) { return from; } @Override public Short copy(Short from, Short reuse) { return from; } @Override public int getLength() { return 2; } @Override public void serialize(Short record, DataOutputView target) throws IOException { target.writeShort(record); } @Override public Short deserialize(DataInputView source) throws IOException { return source.readShort(); } @Override public Short deserialize(Short reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { target.writeShort(source.readShort()); } @Override public TypeSerializerSnapshot snapshotConfiguration() { return new ShortSerializerSnapshot(); } // ------------------------------------------------------------------------ /** * Serializer configuration snapshot for compatibility and format evolution. */ @SuppressWarnings("WeakerAccess") public static final class ShortSerializerSnapshot extends SimpleTypeSerializerSnapshot { public ShortSerializerSnapshot() { super(() -> INSTANCE); } } } |
data class | long method, data class | t | t | t | long method | 0 | 2690 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortSerializer.java/#L32-L104 | 1 | 251 | 2690 | minor | |
| 2304 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicated code 4. Inconsistent formatting/layout 5. Magic numbers/constants 6. Non-descriptive variable names 7. Use of multiple nested if-else statements 8. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method2 Feature envy3 Duplicated code4 Inconsistent formatting/layout5 Magic numbers/constants6 Non-descriptive variable names7 Use of multiple nested if-else statements8 Lack of comments/documentation | t | f | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 2304 | 14061 | major | ||
| 439 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
data class | 1. data class | t | t | f | data class | 0 | 4294 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 439 | 4294 | major | |
| 1139 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/") public class Roles { private Collection roles; public Roles() { } public Roles(Collection roles) { this.roles = roles; } @XmlElementRef public Collection getRoles() { return roles; } public void setRoles(Collection roles) { this.roles = roles; } } |
data class | data class | t | t | t | 0 | 10076 | https://github.com/apache/cxf-fediz/blob/553ae6e3adeb92b7d6300e5c0ad83ed6322e28bd/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java/#L29-L49 | 1 | 1139 | 10076 | major | ||
| 1428 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10949 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 1428 | 10949 | minor | ||
| 609 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String getColumnText(Object element, int columnIndex) { if (element instanceof HadoopServer) { HadoopServer server = (HadoopServer) element; switch (columnIndex) { case 0: return server.getLocationName(); case 1: return server.getMasterHostName().toString(); case 2: return server.getState(); case 3: return ""; } } else if (element instanceof HadoopJob) { HadoopJob job = (HadoopJob) element; switch (columnIndex) { case 0: return job.getJobID().toString(); case 1: return ""; case 2: return job.getState().toString(); case 3: return job.getStatus(); } } else if (element instanceof JarModule) { JarModule jar = (JarModule) element; switch (columnIndex) { case 0: return jar.toString(); case 1: return "Publishing jar to server.."; case 2: return ""; } } return null; } |
long method | long method | t | t | t | 0 | 6124 | https://github.com/apache/hadoop-mapreduce/blob/307cb5b316e10defdbbc228d8cdcdb627191ea15/src/contrib/eclipse-plugin/src/java/org/apache/hadoop/eclipse/view/servers/ServerView.java/#L369-L410 | 1 | 609 | 6124 | minor | ||
| 1313 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected String getGatewayClassName(Element element) { return ((StringUtils.hasText(element.getAttribute("marshaller"))) ? MarshallingWebServiceOutboundGateway.class : SimpleWebServiceOutboundGateway.class).getName(); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 10683 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayParser.java/#L47-L51 | 1 | 1313 | 10683 | critical | |
| 442 | { "output": "YES I found bad smells the bad smells are: 1. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileIODecorator extends AbstractFileIO { /** File I/O delegate */ protected final FileIO delegate; /** * * @param delegate File I/O delegate */ public FileIODecorator(FileIO delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public int getFileSystemBlockSize() { return delegate.getFileSystemBlockSize(); } /** {@inheritDoc} */ @Override public long getSparseSize() { return delegate.getSparseSize(); } /** {@inheritDoc} */ @Override public int punchHole(long pos, int len) { return delegate.punchHole(pos, len); } /** {@inheritDoc} */ @Override public long position() throws IOException { return delegate.position(); } /** {@inheritDoc} */ @Override public void position(long newPosition) throws IOException { delegate.position(newPosition); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf) throws IOException { return delegate.read(destBuf); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf, long position) throws IOException { return delegate.read(destBuf, position); } /** {@inheritDoc} */ @Override public int read(byte[] buf, int off, int len) throws IOException { return delegate.read(buf, off, len); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf) throws IOException { return delegate.write(srcBuf); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf, long position) throws IOException { return delegate.write(srcBuf, position); } /** {@inheritDoc} */ @Override public int write(byte[] buf, int off, int len) throws IOException { return delegate.write(buf, off, len); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int sizeBytes) throws IOException { return delegate.map(sizeBytes); } /** {@inheritDoc} */ @Override public void force() throws IOException { delegate.force(); } /** {@inheritDoc} */ @Override public void force(boolean withMetadata) throws IOException { delegate.force(withMetadata); } /** {@inheritDoc} */ @Override public long size() throws IOException { return delegate.size(); } /** {@inheritDoc} */ @Override public void clear() throws IOException { delegate.clear(); } /** {@inheritDoc} */ @Override public void close() throws IOException { delegate.close(); } } |
blob | 1. blob | t | t | t | 0 | 4303 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/file/FileIODecorator.java/#L27-L123 | 1 | 442 | 4303 | minor | ||
| 2586 | { "output": "YES I found bad smells", "bad smells are": [ "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GangliaServer implements MonitorService { /* * The Ganglia protocol specific stuff: the xdr_* methods * and the sendToGanglia* methods have been shamelessly ripped off * from Hadoop. All hail the yellow elephant! */ private static final Logger logger = LoggerFactory.getLogger(GangliaServer.class); public static final int BUFFER_SIZE = 1500; // as per libgmond.c protected byte[] buffer = new byte[BUFFER_SIZE]; protected int offset; private final List addresses = new ArrayList(); private DatagramSocket socket = null; private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private List hosts; protected final GangliaCollector collectorRunnable; private int pollFrequency = 60; public static final String DEFAULT_UNITS = ""; public static final int DEFAULT_TMAX = 60; public static final int DEFAULT_DMAX = 0; public static final int DEFAULT_SLOPE = 3; public static final String GANGLIA_DOUBLE_TYPE = "double"; private volatile boolean isGanglia3 = false; private String hostname; public final String CONF_POLL_FREQUENCY = "pollFrequency"; public final int DEFAULT_POLL_FREQUENCY = 60; public final String CONF_HOSTS = "hosts"; public final String CONF_ISGANGLIA3 = "isGanglia3"; private static final String GANGLIA_CONTEXT = "flume."; public GangliaServer() throws FlumeException { collectorRunnable = new GangliaCollector(); } /** * Puts a string into the buffer by first writing the size of the string as an * int, followed by the bytes of the string, padded if necessary to a multiple * of 4. * * @param s the string to be written to buffer at offset location */ protected void xdr_string(String s) { byte[] bytes = s.getBytes(); int len = bytes.length; xdr_int(len); System.arraycopy(bytes, 0, buffer, offset, len); offset += len; pad(); } /** * Pads the buffer with zero bytes up to the nearest multiple of 4. */ private void pad() { int newOffset = ((offset + 3) / 4) * 4; while (offset < newOffset) { buffer[offset++] = 0; } } /** * Puts an integer into the buffer as 4 bytes, big-endian. */ protected void xdr_int(int i) { buffer[offset++] = (byte) ((i >> 24) & 0xff); buffer[offset++] = (byte) ((i >> 16) & 0xff); buffer[offset++] = (byte) ((i >> 8) & 0xff); buffer[offset++] = (byte) (i & 0xff); } public synchronized void sendToGangliaNodes() { DatagramPacket packet; for (SocketAddress addr : addresses) { try { packet = new DatagramPacket(buffer, offset, addr); socket.send(packet); } catch (Exception ex) { logger.warn("Could not send metrics to metrics server: " + addr.toString(), ex); } } offset = 0; } /** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start() { try { socket = new DatagramSocket(); hostname = InetAddress.getLocalHost().getHostName(); } catch (SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException( "Could not create socket for metrics collection.", ex); } catch (Exception ex2) { logger.warn("Unknown error occured", ex2); } for (HostInfo host : hosts) { addresses.add(new InetSocketAddress( host.getHostName(), host.getPortNumber())); } collectorRunnable.server = this; if (service.isShutdown() || service.isTerminated()) { service = Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable, 0, pollFrequency, TimeUnit.SECONDS); } /** * Stop this server. */ @Override public void stop() { service.shutdown(); while (!service.isTerminated()) { try { logger.warn("Waiting for ganglia service to stop"); service.awaitTermination(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting" + " for ganglia monitor to shutdown", ex); service.shutdownNow(); } } addresses.clear(); } /** * * @param pollFrequency Seconds between consecutive JMX polls. */ public void setPollFrequency(int pollFrequency) { this.pollFrequency = pollFrequency; } /** * * @return Seconds between consecutive JMX polls */ public int getPollFrequency() { return pollFrequency; } /** * * @param isGanglia3 When true, ganglia 3 messages will be sent, else Ganglia * 3.1 formatted messages are sent. */ public void setIsGanglia3(boolean isGanglia3) { this.isGanglia3 = isGanglia3; } /** * * @return True if the server is currently sending ganglia 3 formatted msgs. * False if the server returns Ganglia 3.1 */ public boolean isGanglia3() { return this.isGanglia3; } protected void createGangliaMessage(String name, String value) { logger.debug("Sending ganglia3 formatted message." + name + ": " + value); name = hostname + "." + name; xdr_int(0); String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); xdr_string(value); xdr_string(DEFAULT_UNITS); xdr_int(DEFAULT_SLOPE); xdr_int(DEFAULT_TMAX); xdr_int(DEFAULT_DMAX); } protected void createGangliaMessage31(String name, String value) { logger.debug("Sending ganglia 3.1 formatted message: " + name + ": " + value); xdr_int(128); // metric_id = metadata_msg xdr_string(hostname); // hostname xdr_string(name); // metric name xdr_int(0); // spoof = False String type = "string"; try { Float.parseFloat(value); type = "float"; } catch (NumberFormatException ex) { // The param is a string, and so leave the type as is. } xdr_string(type); // metric type xdr_string(name); // metric name xdr_string(DEFAULT_UNITS); // units xdr_int(DEFAULT_SLOPE); // slope xdr_int(DEFAULT_TMAX); // tmax, the maximum time between metrics xdr_int(DEFAULT_DMAX); // dmax, the maximum data value xdr_int(1); /*Num of the entries in extra_value field for Ganglia 3.1.x*/ xdr_string("GROUP"); /*Group attribute*/ xdr_string("flume"); /*Group value*/ this.sendToGangliaNodes(); // Now we send out a message with the actual value. // Technically, we only need to send out the metadata message once for // each metric, but I don't want to have to record which metrics we did and // did not send. xdr_int(133); // we are sending a string value xdr_string(hostname); // hostName xdr_string(name); // metric name xdr_int(0); // spoof = False xdr_string("%s"); // format field xdr_string(value); // metric value } @Override public void configure(Context context) { this.pollFrequency = context.getInteger(this.CONF_POLL_FREQUENCY, 60); String localHosts = context.getString(this.CONF_HOSTS); if (localHosts == null || localHosts.isEmpty()) { throw new ConfigurationException("Hosts list cannot be empty."); } this.hosts = this.getHostsFromString(localHosts); this.isGanglia3 = context.getBoolean(this.CONF_ISGANGLIA3, false); } private List getHostsFromString(String hosts) throws FlumeException { List hostInfoList = new ArrayList(); String[] hostsAndPorts = hosts.split(","); int i = 0; for (String host : hostsAndPorts) { String[] hostAndPort = host.split(":"); if (hostAndPort.length < 2) { logger.warn("Invalid ganglia host: ", host); continue; } try { hostInfoList.add(new HostInfo("ganglia_host-" + String.valueOf(i), hostAndPort[0], Integer.parseInt(hostAndPort[1]))); } catch (Exception e) { logger.warn("Invalid ganglia host: " + host, e); continue; } } if (hostInfoList.isEmpty()) { throw new FlumeException("No valid ganglia hosts defined!"); } return hostInfoList; } /** * Worker which polls JMX for all mbeans with * {@link javax.management.ObjectName} within the flume namespace: * org.apache.flume. All attributes of such beans are sent to the all hosts * specified by the server that owns it's instance. * */ protected class GangliaCollector implements Runnable { private GangliaServer server; @Override public void run() { try { Map> metricsMap = JMXPollUtil.getAllMBeans(); for (String component : metricsMap.keySet()) { Map attributeMap = metricsMap.get(component); for (String attribute : attributeMap.keySet()) { if (isGanglia3) { server.createGangliaMessage(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } else { server.createGangliaMessage31(GANGLIA_CONTEXT + component + "." + attribute, attributeMap.get(attribute)); } server.sendToGangliaNodes(); } } } catch (Throwable t) { logger.error("Unexpected error", t); } } } } |
blob | blob | t | t | t | 0 | 14989 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/instrumentation/GangliaServer.java/#L56-L354 | 1 | 2586 | 14989 | critical | ||
| 1091 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Collection collectBasePaths(Iterable targets) { return StreamSupport.stream(targets.spliterator(), false) .map(BuildTarget::getBasePath) .collect(ImmutableSet.toImmutableSet()); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 9728 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/core/model/impl/InMemoryBuildFileTree.java/#L71-L75 | 2 | 1091 | 9728 | major | ||
| 2504 | { "answer": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void validateDepositDetailForUpdate(final JsonElement element, final FromJsonHelper fromApiJsonHelper, final DataValidatorBuilder baseDataValidator) { if (fromApiJsonHelper.parameterExists(nameParamName, element)) { final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (fromApiJsonHelper.parameterExists(shortNameParamName, element)) { final String shortName = fromApiJsonHelper.extractStringNamed(shortNameParamName, element); baseDataValidator.reset().parameter(shortNameParamName).value(shortName).notBlank().notExceedingLengthOf(4); } if (fromApiJsonHelper.parameterExists(descriptionParamName, element)) { final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (fromApiJsonHelper.parameterExists(feeAmountParamName, element)) { final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(feeAmountParamName, element); baseDataValidator.reset().parameter(feeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (fromApiJsonHelper.parameterExists(feeOnMonthDayParamName, element)) { final MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(feeOnMonthDayParamName, element); baseDataValidator.reset().parameter(feeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(minBalanceForInterestCalculationParamName, element)) { final BigDecimal minBalanceForInterestCalculation = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( minBalanceForInterestCalculationParamName, element); baseDataValidator.reset().parameter(minBalanceForInterestCalculationParamName).value(minBalanceForInterestCalculation) .ignoreIfNull().zeroOrPositiveAmount(); } final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); validatePaymentChannelFundSourceMappings(fromApiJsonHelper, baseDataValidator, element); validateChargeToIncomeAccountMappings(fromApiJsonHelper, baseDataValidator, element); validateTaxWithHoldingParams(baseDataValidator, element, false); } |
long method | long method | t | t | t | 0 | 14666 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/DepositProductDataValidator.java/#L413-L547 | 1 | 2504 | 14666 | critical | ||
| 986 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _LocationWebServiceSoap_Connect implements ElementSerializable { // No attributes // Elements protected int connectOptions; protected int lastChangeId; protected int features; public _LocationWebServiceSoap_Connect() { super(); } public _LocationWebServiceSoap_Connect( final int connectOptions, final int lastChangeId, final int features) { // TODO : Call super() instead of setting all fields directly? setConnectOptions(connectOptions); setLastChangeId(lastChangeId); setFeatures(features); } public int getConnectOptions() { return this.connectOptions; } public void setConnectOptions(int value) { this.connectOptions = value; } public int getLastChangeId() { return this.lastChangeId; } public void setLastChangeId(int value) { this.lastChangeId = value; } public int getFeatures() { return this.features; } public void setFeatures(int value) { this.features = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements XMLStreamWriterHelper.writeElement( writer, "connectOptions", this.connectOptions); XMLStreamWriterHelper.writeElement( writer, "lastChangeId", this.lastChangeId); XMLStreamWriterHelper.writeElement( writer, "features", this.features); writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 8880 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/ws/_LocationWebServiceSoap_Connect.java/#L29-L108 | 1 | 986 | 8880 | minor | ||
| 2034 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @AutoValue public abstract static class CreatePayload { public abstract String name(); public abstract Location location(); } |
data class | data class | t | t | t | 0 | 12827 | https://github.com/apache/jclouds/blob/c2670079fabe74f163f43fbade0866469f7a84ec/providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java/#L103-L110 | 1 | 2034 | 12827 | minor | ||
| 1019 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class, long method | t | t | t | long method | 0 | 9341 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 1019 | 9341 | critical | |
| 972 | YES, I found bad smells the bad smells are: 1. Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality. 2. Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary. 3. Indecent Exposure: The fields are not declared as private, making them accessible to other classes. 4. Feature envy: The Capability class seems to be more interested in the fields of the IConvertible interface and functions only as a data class without providing any additional functionality. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality2 Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary3 Indecent Exposure: The fields are not declared as private, making them accessible to other classes4 Feature envy: The Capability class seems to be more interested in the fields of the IConvertible interface and functions only as a data class without providing any additional functionality | t | f | t | . Dead Code: The implementation of the IConvertible interface is empty and does not provide any functionality.2. Accessor Mutator Pair: The get and set methods have been generated for all fields, which may be unnecessary.3. Indecent Exposure: The fields are not declared as private | 0 | 8715 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 2 | 972 | 8715 | major | |
| 15 | {"message": "YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy."} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static String replaceSubstitution(String base, Pattern from, String to, boolean repeat) { Matcher match = from.matcher(base); if (repeat) { return match.replaceAll(to); } else { return match.replaceFirst(to); } } |
feature envy | 1. long method, 2. feature envy. | t | t | t | 1. long method | 0 | 641 | https://github.com/apache/zookeeper/blob/07c3aaf3d723fb3144c0aedc0c2b655325df70e9/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KerberosName.java/#L287-L295 | 2 | 15 | 641 | critical | |
| 971 | { "output": "YES I found bad smells\nthe bad smells are: Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final EObject ruleXOtherOperatorExpression() throws RecognitionException { EObject current = null; EObject this_XAdditiveExpression_0 = null; EObject lv_rightOperand_3_0 = null; enterRule(); try { // InternalXbase.g:873:2: ( (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) ) // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) { // InternalXbase.g:874:2: (this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* ) // InternalXbase.g:875:3: this_XAdditiveExpression_0= ruleXAdditiveExpression ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getXAdditiveExpressionParserRuleCall_0()); } pushFollow(FOLLOW_14); this_XAdditiveExpression_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current = this_XAdditiveExpression_0; afterParserOrEnumRuleCall(); } // InternalXbase.g:883:3: ( ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) )* loop11: do { int alt11=2; alt11 = dfa11.predict(input); switch (alt11) { case 1 : // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) { // InternalXbase.g:884:4: ( ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) ) // InternalXbase.g:885:5: ( ( () ( ( ruleOpOther ) ) ) )=> ( () ( ( ruleOpOther ) ) ) { // InternalXbase.g:895:5: ( () ( ( ruleOpOther ) ) ) // InternalXbase.g:896:6: () ( ( ruleOpOther ) ) { // InternalXbase.g:896:6: () // InternalXbase.g:897:7: { if ( state.backtracking==0 ) { current = forceCreateModelElementAndSet( grammarAccess.getXOtherOperatorExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(), current); } } // InternalXbase.g:903:6: ( ( ruleOpOther ) ) // InternalXbase.g:904:7: ( ruleOpOther ) { // InternalXbase.g:904:7: ( ruleOpOther ) // InternalXbase.g:905:8: ruleOpOther { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXOtherOperatorExpressionRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0()); } pushFollow(FOLLOW_4); ruleOpOther(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } } // InternalXbase.g:921:4: ( (lv_rightOperand_3_0= ruleXAdditiveExpression ) ) // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) { // InternalXbase.g:922:5: (lv_rightOperand_3_0= ruleXAdditiveExpression ) // InternalXbase.g:923:6: lv_rightOperand_3_0= ruleXAdditiveExpression { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXOtherOperatorExpressionAccess().getRightOperandXAdditiveExpressionParserRuleCall_1_1_0()); } pushFollow(FOLLOW_14); lv_rightOperand_3_0=ruleXAdditiveExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getXOtherOperatorExpressionRule()); } set( current, "rightOperand", lv_rightOperand_3_0, "org.eclipse.xtext.xbase.Xbase.XAdditiveExpression"); afterParserOrEnumRuleCall(); } } } } break; default : break loop11; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | long method | t | t | t | 0 | 8713 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/parser/antlr/internal/InternalXbaseParser.java/#L2675-L2841 | 1 | 971 | 8713 | major | ||
| 471 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 4568 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 471 | 4568 | major | ||
| 1188 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 1188 | 10247 | minor | |
| 652 | {"response": "YES I found bad smells. the bad smells are: 2. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ConsoleProxyClientParam { private String clientHostAddress; private int clientHostPort; private String clientHostPassword; private String clientTag; private String ticket; private String locale; private String clientTunnelUrl; private String clientTunnelSession; private String hypervHost; private String ajaxSessionId; private String username; private String password; public ConsoleProxyClientParam() { clientHostPort = 0; } public String getClientHostAddress() { return clientHostAddress; } public void setClientHostAddress(String clientHostAddress) { this.clientHostAddress = clientHostAddress; } public int getClientHostPort() { return clientHostPort; } public void setClientHostPort(int clientHostPort) { this.clientHostPort = clientHostPort; } public String getClientHostPassword() { return clientHostPassword; } public void setClientHostPassword(String clientHostPassword) { this.clientHostPassword = clientHostPassword; } public String getClientTag() { return clientTag; } public void setClientTag(String clientTag) { this.clientTag = clientTag; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getClientTunnelUrl() { return clientTunnelUrl; } public void setClientTunnelUrl(String clientTunnelUrl) { this.clientTunnelUrl = clientTunnelUrl; } public String getClientTunnelSession() { return clientTunnelSession; } public void setClientTunnelSession(String clientTunnelSession) { this.clientTunnelSession = clientTunnelSession; } public String getAjaxSessionId() { return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } public void setHypervHost(String host) { hypervHost = host; } public String getHypervHost() { return hypervHost; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
data class | 2. data class | t | t | t | 0 | 6386 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java/#L20-L143 | 1 | 652 | 6386 | critical | ||
| 460 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1131 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1131() {} public Customer1131(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1131[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 4462 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1131.java/#L8-L27 | 1 | 460 | 4462 | minor | ||
| 2006 | {"response":"YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | 1. long method | t | t | f | long method | 0 | 12721 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 2006 | 12721 | major | |
| 2037 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void crawl(File dirRoot) { LOG.info(String.format("Start crawling dir: %s", dirRoot)); // Reset ingest status.a ingestStatus.clear(); // Load actions. loadAndValidateActions(); // Create Ingester. setupIngester(); // Verify valid crawl directory. if (dirRoot == null || !dirRoot.exists()) { throw new IllegalArgumentException("dir root is null or non existant!"); } // Start crawling. Stack stack = new Stack(); stack.push(dirRoot.isDirectory() ? dirRoot : dirRoot.getParentFile()); while (!stack.isEmpty()) { File dir = (File) stack.pop(); LOG.log(Level.INFO, "Crawling " + dir); File[] productFiles; productFiles = isCrawlForDirs() ? dir.listFiles(DIR_FILTER) : dir.listFiles(FILE_FILTER); if(productFiles!=null) { for (File productFile : productFiles) { ingestStatus.add(handleFile(productFile)); } } if (!isNoRecur()) { File[] subdirs = dir.listFiles(DIR_FILTER); if (subdirs != null) { for (File subdir : subdirs) { stack.push(subdir); } } } } LOG.info(String.format("Finished crawling dir: %s", dirRoot)); } |
long method | long method | t | t | t | 0 | 12838 | https://github.com/apache/oodt/blob/9f2a500b9d061c31ccd71fc66c4d6e40f0c25acb/crawler/src/main/java/org/apache/oodt/cas/crawl/ProductCrawler.java/#L79-L124 | 1 | 2037 | 12838 | minor | ||
| 491 | { "output": "YES I found bad smells. The bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | 1. long method | t | t | f | long method | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 1 | 491 | 4899 | major | |
| 336 | YES I found bad smells The bad smells are: 1. Long Method 2. Feature Envy 3. Duplicate Code 4. Inconsistent Indentation 5. Primitive Obsession 6. Magic Numbers 7. Bloated code with unnecessary if-else statements | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private synchronized void checkHealth() { CalculatedStatus status = calculateStatus(); boolean healthy = status.isHealthy(); long now = System.currentTimeMillis(); if (healthy) { stateLastGood.set(now); if (lastPublished == LastPublished.FAILED) { if (currentRecoveryStartTime == null) { LOG.info("{} check for {}, now recovering: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing recovering: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentFailureStartTime != null) { LOG.info("{} check for {}, now healthy: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still healthy: {}", new Object[] {this, entity, getDescription(status)}); } } } else { stateLastFail.set(now); if (lastPublished != LastPublished.FAILED) { if (currentFailureStartTime == null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentFailureStartTime = now; schedulePublish(); } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, continuing failing: {}", new Object[] {this, entity, getDescription(status)}); } } else { if (currentRecoveryStartTime != null) { LOG.info("{} check for {}, now failing: {}", new Object[] {this, entity, getDescription(status)}); currentRecoveryStartTime = null; } else { if (LOG.isTraceEnabled()) LOG.trace("{} check for {}, still failed: {}", new Object[] {this, entity, getDescription(status)}); } } } } |
long method | Long Method 2 Feature Envy 3 Duplicate Code 4 Inconsistent Indentation 5 Primitive Obsession 6 Magic Numbers 7 Bloated code with unnecessary if-else statements | t | f | t | 0 | 3447 | https://github.com/apache/brooklyn-server/blob/880eb1da00f6358d7fd76d065322e3685bfb1a04/policy/src/main/java/org/apache/brooklyn/policy/ha/AbstractFailureDetector.java/#L223-L265 | 2 | 336 | 3447 | minor | ||
| 2675 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class IntermediateModel { private final Metadata metadata; private final Map operations; private final Map shapes; private final CustomizationConfig customizationConfig; private final ServiceExamples examples; private final Map customAuthorizers; @JsonIgnore private final Optional endpointOperation; @JsonIgnore private final Map paginators; @JsonIgnore private final NamingStrategy namingStrategy; @JsonCreator public IntermediateModel( @JsonProperty("metadata") Metadata metadata, @JsonProperty("operations") Map operations, @JsonProperty("shapes") Map shapes, @JsonProperty("customizationConfig") CustomizationConfig customizationConfig, @JsonProperty("serviceExamples") ServiceExamples examples) { this(metadata, operations, shapes, customizationConfig, examples, null, Collections.emptyMap(), Collections.emptyMap(), null); } public IntermediateModel( Metadata metadata, Map operations, Map shapes, CustomizationConfig customizationConfig, ServiceExamples examples, OperationModel endpointOperation, Map customAuthorizers, Map paginators, NamingStrategy namingStrategy) { this.metadata = metadata; this.operations = operations; this.shapes = shapes; this.customizationConfig = customizationConfig; this.examples = examples; this.endpointOperation = Optional.ofNullable(endpointOperation); this.customAuthorizers = customAuthorizers; this.paginators = paginators; this.namingStrategy = namingStrategy; } public Metadata getMetadata() { return metadata; } public Map getOperations() { return operations; } public OperationModel getOperation(String operationName) { return getOperations().get(operationName); } public Map getShapes() { return shapes; } public ShapeModel getShapeByC2jName(String c2jName) { return Utils.findShapeModelByC2jName(this, c2jName); } public CustomizationConfig getCustomizationConfig() { return customizationConfig; } public ServiceExamples getExamples() { return examples; } public Map getPaginators() { return paginators; } public NamingStrategy getNamingStrategy() { return namingStrategy; } public String getCustomRetryPolicy() { return customizationConfig.getCustomRetryPolicy(); } public String getSdkModeledExceptionBaseFqcn() { return String.format("%s.%s", metadata.getFullModelPackageName(), getSdkModeledExceptionBaseClassName()); } public String getSdkModeledExceptionBaseClassName() { if (customizationConfig.getSdkModeledExceptionBaseClassName() != null) { return customizationConfig.getSdkModeledExceptionBaseClassName(); } else { return metadata.getBaseExceptionName(); } } public String getSdkRequestBaseClassName() { if (customizationConfig.getSdkRequestBaseClassName() != null) { return customizationConfig.getSdkRequestBaseClassName(); } else { return metadata.getBaseRequestName(); } } public String getSdkResponseBaseClassName() { if (customizationConfig.getSdkResponseBaseClassName() != null) { return customizationConfig.getSdkResponseBaseClassName(); } else { return metadata.getBaseResponseName(); } } public String getFileHeader() throws IOException { return loadDefaultFileHeader(); } private String loadDefaultFileHeader() throws IOException { try (InputStream inputStream = getClass() .getResourceAsStream("/software/amazon/awssdk/codegen/DefaultFileHeader.txt")) { return IoUtils.toUtf8String(inputStream) .replaceFirst("%COPYRIGHT_DATE_RANGE%", getCopyrightDateRange()); } } private String getCopyrightDateRange() { int currentYear = ZonedDateTime.now().getYear(); int copyrightStartYear = currentYear - 5; return String.format("%d-%d", copyrightStartYear, currentYear); } public String getSdkBaseResponseFqcn() { if (metadata.getProtocol() == Protocol.API_GATEWAY) { return "software.amazon.awssdk.opensdk.BaseResult"; } else { return String.format("%s<%s>", AwsResponse.class.getName(), getResponseMetadataClassName()); } } private String getResponseMetadataClassName() { return AwsResponseMetadata.class.getName(); } @JsonIgnore public List simpleMethodsRequiringTesting() { return getOperations().values().stream() .filter(v -> v.getInputShape().isSimpleMethod()) .collect(Collectors.toList()); } public Map getCustomAuthorizers() { return customAuthorizers; } public Optional getEndpointOperation() { return endpointOperation; } public boolean hasPaginators() { return paginators.size() > 0; } public boolean containsRequestSigners() { return getShapes().values().stream() .filter(ShapeModel::isRequestSignerAware) .findAny() .isPresent(); } public boolean containsRequestEventStreams() { return getOperations().values().stream() .filter(opModel -> opModel.hasEventStreamInput()) .findAny() .isPresent(); } } |
data class | data class | t | t | t | 0 | 15229 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/intermediate/IntermediateModel.java/#L37-L226 | 1 | 2675 | 15229 | major | ||
| 197 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | 1. long method | t | t | t | 0 | 2237 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 197 | 2237 | minor | ||
| 347 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int)Math.ceil((float)encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte)(b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } |
long method | Long method | t | f | t | 0 | 3549 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/mosgi/jmx.agent/src/main/java/org/apache/felix/mosgi/jmx/agent/mx4j/util/Base64Codec.java/#L218-L377 | 2 | 347 | 3549 | major | ||
| 119 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult) { this.bindingResult = (BindingResult) this.errors; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException("Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String) { this.value = HtmlUtils.htmlEscape((String) this.value); } } |
long method | 1. long method | t | t | t | 0 | 1514 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-webmvc/src/main/java/org/springframework/web/servlet/support/BindStatus.java/#L96-L169 | 1 | 119 | 1514 | major | ||
| 998 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 2 | 998 | 9158 | minor | ||
| 868 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Conditional complexity, 4. Long parameter list, 5. Cognitive complexity, 6. Duplicated code, 7. Data clumps. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
feature envy | Long method, 2 Feature envy, 3 Conditional complexity, 4 Long parameter list, 5 Cognitive complexity, 6 Duplicated code, 7 Data clumps | t | f | t | . Long method, 3. Conditional complexity, 4. Long parameter list, 5. Cognitive complexity, 6. Duplicated code, 7. Data clumps. | 0 | 7947 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 868 | 7947 | minor | |
| 873 | YES, I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy 4. Inconsistent indentation 5. Inconsistent naming conventions 6. Magic numbers 7. Useless comments 8. Unnecessary temporary variables 9. Nested conditionals 10. Coupled code 11. Strong coupling 12. Contrived complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void validateTwoSegments(final IndexableAdapter adapter1, final IndexableAdapter adapter2) { if (adapter1.getNumRows() != adapter2.getNumRows()) { throw new SegmentValidationException( "Row count mismatch. Expected [%d] found [%d]", adapter1.getNumRows(), adapter2.getNumRows() ); } { final Set dimNames1 = Sets.newHashSet(adapter1.getDimensionNames()); final Set dimNames2 = Sets.newHashSet(adapter2.getDimensionNames()); if (!dimNames1.equals(dimNames2)) { throw new SegmentValidationException( "Dimension names differ. Expected [%s] found [%s]", dimNames1, dimNames2 ); } final Set metNames1 = Sets.newHashSet(adapter1.getMetricNames()); final Set metNames2 = Sets.newHashSet(adapter2.getMetricNames()); if (!metNames1.equals(metNames2)) { throw new SegmentValidationException("Metric names differ. Expected [%s] found [%s]", metNames1, metNames2); } } final RowIterator it1 = adapter1.getRows(); final RowIterator it2 = adapter2.getRows(); long row = 0L; while (it1.moveToNext()) { if (!it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of second adapter"); } final RowPointer rp1 = it1.getPointer(); final RowPointer rp2 = it2.getPointer(); ++row; if (rp1.getRowNum() != rp2.getRowNum()) { throw new SegmentValidationException("Row number mismatch: [%d] vs [%d]", rp1.getRowNum(), rp2.getRowNum()); } try { validateRowValues(rp1, adapter1, rp2, adapter2); } catch (SegmentValidationException ex) { throw new SegmentValidationException(ex, "Validation failure on row %d: [%s] vs [%s]", row, rp1, rp2); } } if (it2.moveToNext()) { throw new SegmentValidationException("Unexpected end of first adapter"); } if (row != adapter1.getNumRows()) { throw new SegmentValidationException( "Actual Row count mismatch. Expected [%d] found [%d]", row, adapter1.getNumRows() ); } } |
feature envy | Long method2 Duplicate code 3 Feature envy4 Inconsistent indentation5 Inconsistent naming conventions6 Magic numbers 7 Useless comments 8 Unnecessary temporary variables 9 Nested conditionals | t | f | t | 0 | 7982 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/IndexIO.java/#L124-L179 | 2 | 873 | 7982 | major | ||
| 449 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | Long method | t | f | t | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 2 | 449 | 4369 | major | ||
| 936 | {"message": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TfsGitTreeEntriesJson { private final String objectId; private final List treeEntries; private final int size; @JsonCreator public TfsGitTreeEntriesJson( @JsonProperty("objectId") final String objectId, @JsonProperty("treeEntries") final List treeEntries, @JsonProperty("size") final int size) throws JsonProcessingException { this.objectId = objectId; this.treeEntries = treeEntries; this.size = size; } public String getObjectId() { return objectId; } public List getTreeEntries() { return treeEntries; } public int getSize() { return size; } } |
data class | blob, data class | t | t | t | blob | 0 | 8410 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common/src/com/microsoft/tfs/client/common/git/json/TfsGitTreeEntriesJson.java/#L12-L38 | 1 | 936 | 8410 | major | |
| 2259 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13703 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 2259 | 13703 | minor | |
| 606 | YES I found bad smells The bad smells are: 1. Long method 2. Magic number (128 * 1024) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | Long method2 Magic number ( | t | f | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 2 | 606 | 6083 | minor | ||
| 2420 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14428 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 2420 | 14428 | minor | |
| 569 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method" }, { "2. Feature Envy": "Feature Envy" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
long method | 1. long method: long method, 2. feature envy: feature envy | t | t | t | 2. feature envy: feature envy | 0 | 5727 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 1 | 569 | 5727 | major | |
| 2654 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SubProcessCommandLineArgs { // Parameters to pass to the sub-process private List parameters = Lists.newArrayList(); public void addCommand(Integer position, String value) { parameters.add(new Command(position, value)); } public void putCommand(Command command) { parameters.add(command); } public List getParameters() { return parameters; } /** Class used to store the SubProcces parameters. */ public static class Command { // The ordinal position of the command to pass to the sub-process int ordinalPosition; String value; @SuppressWarnings("unused") private Command() {} public Command(int ordinalPosition, String value) { this.ordinalPosition = ordinalPosition; this.value = value; } public int getKey() { return ordinalPosition; } public void setKey(int key) { this.ordinalPosition = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } |
data class | data class, long method | t | t | t | long method | 0 | 15180 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/examples/java/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessCommandLineArgs.java/#L24-L72 | 1 | 2654 | 15180 | minor | |
| 1451 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 2 | 1451 | 11000 | minor | ||
| 1399 | YES, I found bad smells. 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10858 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 1399 | 10858 | major | ||
| 1084 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void createServerIdEditGroup( Composite parent ) { // ServerID Group Group serverIdGroup = BaseWidgetUtils.createGroup( parent, "ServerID input", 1 ); GridLayout serverIdGroupGridLayout = new GridLayout( 2, false ); serverIdGroup.setLayout( serverIdGroupGridLayout ); serverIdGroup.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // ServerID Text BaseWidgetUtils.createLabel( serverIdGroup, "ID:", 1 ); idText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); // URL Text BaseWidgetUtils.createLabel( serverIdGroup, "URL:", 1 ); urlText = BaseWidgetUtils.createText( serverIdGroup, "", 1 ); urlText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9692 | https://github.com/apache/directory-studio/blob/e8f15ea553a3ae7bebc2fe96d6a2864e188f8017/plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/dialogs/ServerIdDialog.java/#L239-L256 | 2 | 1084 | 9692 | minor | ||
| 998 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private V1SelfSubjectAccessReview prepareSelfSubjectAccessReview( Operation operation, Resource resource, String resourceName, Scope scope, String namespaceName) { LOGGER.entering(); V1SelfSubjectAccessReviewSpec subjectAccessReviewSpec = new V1SelfSubjectAccessReviewSpec(); subjectAccessReviewSpec.setResourceAttributes( prepareResourceAttributes(operation, resource, resourceName, scope, namespaceName)); V1SelfSubjectAccessReview subjectAccessReview = new V1SelfSubjectAccessReview(); subjectAccessReview.setApiVersion("authorization.k8s.io/v1"); subjectAccessReview.setKind("SelfSubjectAccessReview"); subjectAccessReview.setMetadata(new V1ObjectMeta()); subjectAccessReview.setSpec(subjectAccessReviewSpec); LOGGER.exiting(subjectAccessReview); return subjectAccessReview; } |
long method | long method | t | t | t | 0 | 9158 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/AuthorizationProxy.java/#L239-L258 | 1 | 998 | 9158 | minor | ||
| 1003 | {"response": "YES I found bad smells, the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleRemainder() { final int remainingRecordCount = incoming.getRecordCount() - remainderIndex; assert this.memoryManager.incomingBatch == incoming; final int recordsToProcess = Math.min(remainingRecordCount, memoryManager.getOutputRowCount()); if (!doAlloc(recordsToProcess)) { outOfMemory = true; return; } logger.trace("handleRemainder: remaining RC {}, toProcess {}, remainder index {}, incoming {}, Project {}", remainingRecordCount, recordsToProcess, remainderIndex, incoming, this); long projectStartTime = System.currentTimeMillis(); final int projRecords = projector.projectRecords(this.incoming, remainderIndex, recordsToProcess, 0); long projectEndTime = System.currentTimeMillis(); logger.trace("handleRemainder: projection: records {}, time {} ms", projRecords,(projectEndTime - projectStartTime)); if (projRecords < remainingRecordCount) { setValueCount(projRecords); this.recordCount = projRecords; remainderIndex += projRecords; } else { setValueCount(remainingRecordCount); hasRemainder = false; remainderIndex = 0; for (final VectorWrapper v : incoming) { v.clear(); } this.recordCount = remainingRecordCount; } // In case of complex writer expression, vectors would be added to batch run-time. // We have to re-build the schema. if (complexWriters != null) { container.buildSchema(SelectionVectorMode.NONE); } memoryManager.updateOutgoingStats(projRecords); RecordBatchStats.logRecordBatchStats(RecordBatchIOType.OUTPUT, this, getRecordBatchStatsContext()); } |
long method | 1. long method | t | t | t | 0 | 9230 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java/#L259-L299 | 1 | 1003 | 9230 | minor | ||
| 1155 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Inconsistent naming, 6. Incomplete commenting, 7. Unused variables, 8. Empty catch block, 9. Unnecessary comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
feature envy | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Inconsistent naming, 6 Incomplete commenting, 7 Unused variables, 8 Empty catch block, 9 Unnecessary comments | t | f | t | . Long method, 3. Duplicate code, 4. Magic numbers, 5. Inconsistent naming, 6. Incomplete commenting, 7. Unused variables, 8. Empty catch block, 9. Unnecessary comments. | 0 | 10138 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 1155 | 10138 | critical | |
| 589 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean readFont(FontFileReader in, String header, String name) throws IOException { initializeFont(in); /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(header, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(); readFontHeader(); getNumGlyphs(); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(); readHorizontalMetrics(); initAnsiWidths(); readPostScript(); readOS2(); determineAscDesc(); readName(); boolean pcltFound = readPCLT(); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); updateBBoxAndOffset(); if (useKerning) { readKerning(); } handleCharacterSpacing(in); guessVerticalMetricsFromGlyphBBox(); return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5882 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/fonts/truetype/OpenFont.java/#L813-L862 | 2 | 589 | 5882 | minor | ||
| 2623 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | data class | t | t | t | 0 | 15063 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 2623 | 15063 | minor | ||
| 1373 | YES I found bad smells, The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Long method2 Feature envy | t | f | t | 0 | 10803 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 1373 | 10803 | critical | ||
| 2451 | YES I found bad smells bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 14506 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2451 | 14506 | minor | |
| 637 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String getDeviceDisplayName() { String displayName = ""; if (this.properties == null) { return displayName; } String deviceDisplayNameOption = (String) this.properties.get(DEVICE_DISPLAY_NAME); // Use the device name from SystemService. This should be kura.device.name from // the properties file. if ("device-name".equals(deviceDisplayNameOption)) { displayName = this.systemService.getDeviceName(); } // Try to get the device hostname else if ("hostname".equals(deviceDisplayNameOption)) { displayName = this.systemService.getHostname(); } // Return the custom field defined by the user else if ("custom".equals(deviceDisplayNameOption) && this.properties.get(DEVICE_CUSTOM_NAME) instanceof String) { displayName = (String) this.properties.get(DEVICE_CUSTOM_NAME); } // Return empty string to the server else if ("server".equals(deviceDisplayNameOption)) { displayName = ""; } return displayName; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6316 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core.cloud/src/main/java/org/eclipse/kura/core/cloud/CloudServiceOptions.java/#L64-L91 | 2 | 637 | 6316 | minor | ||
| 2376 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | long method | t | t | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 1 | 2376 | 14325 | minor | ||
| 3479 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 1 | 3479 | 7119 | minor | |
| 257 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String command() { String flags; if (add) { flags = " +FLAGS "; } else if (subtract) { flags = " -FLAGS "; } else { flags = " FLAGS "; } if (silent) { flags = flags + ".SILENT"; } return "STORE " + msn + flags + this.flags + ")"; } |
long method | long method | t | t | t | 0 | 2777 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mpt/core/src/main/java/org/apache/james/mpt/helper/ScriptBuilder.java/#L604-L617 | 1 | 257 | 2777 | minor | ||
| 2104 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: // System.out.println(" skip rewind!"); // } } assert length == f.prefix; assert termOrd == f.termOrdOrig; } else { f.nextEnt = -1; f.prefix = length; f.state.termBlockOrd = 0; f.termOrdOrig = termOrd; // System.out.println("set termOrdOrig=" + termOrd); f.termOrd = termOrd; f.fpOrig = f.fp = fp; f.lastSubFP = -1; // if (DEBUG) { // final int sav = term.length; // term.length = length; // System.out.println(" push new frame ord=" + f.ord + " fp=" + f.fp + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " pref=" + brToString(term)); // term.length = sav; // } } return f; } // asserts only private boolean clearEOF() { eof = false; return true; } // asserts only private boolean setEOF() { eof = true; return true; |
long method | Long method | t | f | t | 0 | 13168 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java/#L174-L208 | 2 | 2104 | 13168 | minor | ||
| 933 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NewItemFinishEvent extends NewItemEvent { private static final String EVENT_DESCRIPTION = "finish"; private Serializable result; public NewItemFinishEvent(final T item, final AjaxRequestTarget target) { super(item, target); } @Override public String getEventDescription() { return NewItemFinishEvent.EVENT_DESCRIPTION; } public NewItemFinishEvent setResult(final Serializable result) { this.result = result; return this; } public Serializable getResult() { return result; } } |
data class | data class | t | t | t | 0 | 8372 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/client/idrepo/ui/src/main/java/org/apache/syncope/client/ui/commons/wizards/AjaxWizard.java/#L344-L367 | 1 | 933 | 8372 | minor | ||
| 173 | { "response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | long method, data class | t | t | t | data class | 0 | 2041 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 1 | 173 | 2041 | minor | |
| 2061 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | 1. data class | t | t | f | data class | 0 | 12970 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 2061 | 12970 | major | |
| 1682 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } ImmutableBitSet streaming = streamingBuilder.build(); final double cpuCost = algoUtils.computeBucketMapJoinCPUCost(cardinalities, streaming); // 3. IO cost = cost of transferring small tables to join node * // degree of parallelism final Double leftRAverageSize = mq.getAverageRowSize(join.getLeft()); final Double rightRAverageSize = mq.getAverageRowSize(join.getRight()); if (leftRAverageSize == null || rightRAverageSize == null) { return null; } ImmutableList> relationInfos = new ImmutableList.Builder>(). add(new Pair(leftRCount,leftRAverageSize)). add(new Pair(rightRCount,rightRAverageSize)). build(); //TODO: No Of buckets is not same as no of splits JoinAlgorithm oldAlgo = join.getJoinAlgorithm(); join.setJoinAlgorithm(TezBucketJoinAlgorithm.INSTANCE); final int parallelism = mq.splitCount(join) == null ? 1 : mq.splitCount(join); join.setJoinAlgorithm(oldAlgo); final double ioCost = algoUtils.computeBucketMapJoinIOCost(relationInfos, streaming, parallelism); // 4. Result return HiveCost.FACTORY.makeCost(rCount, cpuCost, ioCost); } @Override public ImmutableList getCollation(HiveJoin join) { final MapJoinStreamingRelation streamingSide = join.getStreamingSide(); if (streamingSide != MapJoinStreamingRelation.LEFT_RELATION && streamingSide != MapJoinStreamingRelation.RIGHT_RELATION) { // Error; default value LOG.warn("Streaming side for map join not chosen"); return ImmutableList.of(); } return HiveAlgorithmsUtil.getJoinCollation(join.getJoinPredicateInfo(), join.getStreamingSide()); } @Override public RelDistribution getDistribution(HiveJoin join) { return HiveAlgorithmsUtil.getJoinRedistribution(join.getJoinPredicateInfo()); } @Override public Double getMemory(HiveJoin join) { return HiveAlgorithmsUtil.getJoinMemory(join); } @Override public Double getCumulativeMemoryWithinPhaseSplit(HiveJoin join) { |
long method | Data Class, Long Method | t | f | t | Data Class | 0 | 11682 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/cost/HiveOnTezCostModel.java/#L414-L464 | 1 | 1682 | 11682 | major | |
| 5531 | { "message": "YES I found bad smells", "bad smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5531 | 5816 | minor | |
| 381 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean isVisible(final IStructuredSelection selection) { final ChangeItem[] changes = (ChangeItem[]) SelectionUtils.selectionToArray(getSelection(), ChangeItem.class); // Enable for any delete for (final ChangeItem change : changes) { if (change.getChangeType().contains(ChangeType.DELETE)) { return true; } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3908 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/dialogs/vc/candidates/RestoreAction.java/#L55-L66 | 2 | 381 | 3908 | minor | ||
| 730 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RealRowResultSetStatistics extends RealNoPutResultSetStatistics { /* Leave these fields public for object inspectors */ public int rowsReturned; // CONSTRUCTORS /** * * */ public RealRowResultSetStatistics( int numOpens, int rowsSeen, int rowsFiltered, long constructorTime, long openTime, long nextTime, long closeTime, int resultSetNumber, int rowsReturned, double optimizerEstimatedRowCount, double optimizerEstimatedCost ) { super( numOpens, rowsSeen, rowsFiltered, constructorTime, openTime, nextTime, closeTime, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost ); this.rowsReturned = rowsReturned; } // ResultSetStatistics methods /** * Return the statement execution plan as a String. * * @param depth Indentation level. * * @return String The statement execution plan as a String. */ public String getStatementExecutionPlanText(int depth) { initFormatInfo(depth); return indent + MessageService.getTextMessage(SQLState.RTS_ROW_RS) + ":\n" + indent + MessageService.getTextMessage(SQLState.RTS_NUM_OPENS) + " = " + numOpens + "\n" + indent + MessageService.getTextMessage( SQLState.RTS_ROWS_RETURNED) + " = " + rowsReturned + "\n" + dumpTimeStats(indent, subIndent) + "\n" + dumpEstimatedCosts(subIndent) + "\n"; } /** * Return information on the scan nodes from the statement execution * plan as a String. * * @param depth Indentation level. * @param tableName if not NULL then print information for this table only * * @return String The information on the scan nodes from the * statement execution plan as a String. */ public String getScanStatisticsText(String tableName, int depth) { return ""; } // Class implementation public String toString() { return getStatementExecutionPlanText(0); } /** * Format for display, a name for this node. * */ public String getNodeName(){ return MessageService.getTextMessage(SQLState.RTS_ROW_RS); } // ----------------------------------------------------- // XPLAINable Implementation // ----------------------------------------------------- public void accept(XPLAINVisitor visitor) { // I have no children, inform my visitor about that visitor.setNumberOfChildren(0); // pre-order, depth-first traversal // me first visitor.visit(this); // I'm a leaf node, I have no children ... } public String getRSXplainType() { return XPLAINUtil.OP_ROW; } public Object getResultSetDescriptor(Object rsID, Object parentID, Object scanID, Object sortID, Object stmtID, Object timingID) { return new XPLAINResultSetDescriptor( (UUID)rsID, getRSXplainType(), getRSXplainDetails(), this.numOpens, null, // the number of index updates null, // lock mode null, // lock granularity (UUID)parentID, this.optimizerEstimatedRowCount, this.optimizerEstimatedCost, null, // the affected rows null, // the deferred rows null, // the input rows this.rowsSeen, null, // the seen rows right this.rowsFiltered, this.rowsReturned, null, // the empty right rows null, // index key optimization (UUID)scanID, (UUID)sortID, (UUID)stmtID, (UUID)timingID); } } |
data class | 1. data class | t | t | t | 0 | 6866 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/rts/RealRowResultSetStatistics.java/#L46-L187 | 1 | 730 | 6866 | minor | ||
| 1345 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10747 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 1345 | 10747 | minor | |
| 1227 | YES I found bad smells the bad smells are: 1. Commented out code 2. Long method 3. Feature envy 4. Inconsistent indentation 5. Non-descriptive variable names 6. Nested if statements 7. Lack of error handling for exceptions 8. Multiple responsibilities in one method (parsing, handling exceptions, building results map) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Commented out code2 Long method3 Feature envy4 Inconsistent indentation5 Non-descriptive variable names6 Nested if statements7 Lack of error handling for exceptions8 Multiple responsibilities in one method (parsing, handling exceptions, building results map) | t | f | t | handling exceptions, building results map) | 0 | 10353 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1227 | 10353 | major | |
| 1956 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { try { if (isConnected() && (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) { synchronized (this) { Participant participant = leaderLatch.getLeader(); if (isLeader(participant) && !leaderLatch.hasLeadership()) { // in case current instance becomes leader, we want to know who came before it. currentLeader = participant; } } } } catch (InterruptedException e) { log.warn("Oracle leadership watcher has been interrupted unexpectedly"); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12558 | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/oracle/OracleServer.java/#L448-L467 | 2 | 1956 | 12558 | minor | ||
| 2117 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Comments 4. Magic numbers 5. Use of raw types | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Feature envy 2 Long method 3 Comments 4 Magic numbers 5 Use of raw types | t | f | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 2117 | 13197 | major | ||
| 534 | {"message": "YES I found bad smells the bad smells are: 2. Data class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | 2. data class | t | t | f | data class | 0 | 5480 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 534 | 5480 | major | |
| 2140 | {"response": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class NexmarkQueryTransform extends PTransform, PCollection> { private transient PCollection> sideInput = null; protected NexmarkQueryTransform(String name) { super(name); } /** Whether this query expects a side input to be populated. Defaults to {@code false}. */ public boolean needsSideInput() { return false; } /** * Set the side input for the query. * * Note that due to the nature of side inputs, this instance of the query is now fixed and can * only be safely applied in the pipeline where the side input was created. */ public void setSideInput(PCollection> sideInput) { this.sideInput = sideInput; } /** Get the side input, if any. */ public @Nullable PCollection> getSideInput() { return sideInput; } } |
data class | data class | t | t | t | 0 | 13264 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/NexmarkQueryTransform.java/#L34-L62 | 1 | 2140 | 13264 | minor | ||
| 762 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7113 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 762 | 7113 | major | |
| 318 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: // count the number of '/'s, to determine number of segments int index = -1; int pathlen = path.length(); int size = 0; if (pathlen > 0 && path.charAt(0) != '/') { size++; } while ((index = path.indexOf('/', index + 1)) != -1) { if (index + 1 < pathlen && path.charAt(index + 1) != '/') { size++; } } String[] seglist = new String[size]; boolean[] include = new boolean[size]; // break the path into segments and store in the list int current = 0; int index2 = 0; index = (pathlen > 0 && path.charAt(0) == '/') ? 1 : 0; while ((index2 = path.indexOf('/', index + 1)) != -1) { seglist[current++] = path.substring(index, index2); index = index2 + 1; } // if current==size, then the last character was a slash // and there are no more segments if (current < size) { seglist[current] = path.substring(index); } // determine which segments get included in the normalized path for (int i = 0; i < size; i++) { include[i] = true; if (seglist[i].equals("..")) { //$NON-NLS-1$ int remove = i - 1; // search back to find a segment to remove, if possible while (remove > -1 && !include[remove]) { remove--; } // if we find a segment to remove, remove it and the ".." // segment if (remove > -1 && !seglist[remove].equals("..")) { //$NON-NLS-1$ include[remove] = false; include[i] = false; } } else if (seglist[i].equals(".")) { //$NON-NLS-1$ include[i] = false; } } // put the path back together StringBuilder newpath = new StringBuilder(); if (path.startsWith("/")) { //$NON-NLS-1$ newpath.append('/'); } for (int i = 0; i < seglist.length; i++) { if (include[i]) { newpath.append(seglist[i]); newpath.append('/'); } } // if we used at least one segment and the path previously ended with // a slash and the last segment is still used, then delete the extra // trailing '/' if (!path.endsWith("/") && seglist.length > 0 //$NON-NLS-1$ && include[seglist.length - 1]) { newpath.deleteCharAt(newpath.length() - 1); } String result = newpath.toString(); // check for a ':' in the first segment if one exists, // prepend "./" to normalize index = result.indexOf(':'); index2 = result.indexOf('/'); if (index != -1 && (index < index2 || index2 == -1)) { newpath.insert(0, "./"); //$NON-NLS-1$ result = newpath.toString(); } return result; } |
long method | long method | t | t | t | 0 | 3262 | https://github.com/apache/shindig/blob/8f3c3d5c77f5324bad56a5a62da28657fe9112a0/java/common/src/main/java/org/apache/shindig/common/uri/Uri.java/#L205-L289 | 1 | 318 | 3262 | critical | ||
| 1606 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Blob", "2. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
blob | 1. blob, 2. long method | t | t | t | 2. long method | 0 | 11448 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 1606 | 11448 | major | |
| 335 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method 2 Feature Envy | t | f | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 335 | 3439 | major | ||
| 2490 | {"message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SSLConfigClient extends SSLConfig { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SSLConfigClient.class); private final Properties properties; private final boolean userSslEnabled; private final String trustStoreType; private final String trustStorePath; private final String trustStorePassword; private final boolean disableHostVerification; private final boolean disableCertificateVerification; private final boolean useSystemTrustStore; private final String protocol; private final int handshakeTimeout; private final String provider; private final String emptyString = new String(); public SSLConfigClient(Properties properties) throws DrillException { this.properties = properties; userSslEnabled = getBooleanProperty(DrillProperties.ENABLE_TLS); trustStoreType = getStringProperty(DrillProperties.TRUSTSTORE_TYPE, "JKS"); trustStorePath = getStringProperty(DrillProperties.TRUSTSTORE_PATH, ""); trustStorePassword = getStringProperty(DrillProperties.TRUSTSTORE_PASSWORD, ""); disableHostVerification = getBooleanProperty(DrillProperties.DISABLE_HOST_VERIFICATION); disableCertificateVerification = getBooleanProperty(DrillProperties.DISABLE_CERT_VERIFICATION); useSystemTrustStore = getBooleanProperty(DrillProperties.USE_SYSTEM_TRUSTSTORE); protocol = getStringProperty(DrillProperties.TLS_PROTOCOL, DEFAULT_SSL_PROTOCOL); int hsTimeout = getIntProperty(DrillProperties.TLS_HANDSHAKE_TIMEOUT, DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS); if (hsTimeout <= 0) { hsTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT_MS; } handshakeTimeout = hsTimeout; // If provider is OPENSSL then to debug or run this code in an IDE, you will need to enable // the dependency on netty-tcnative with the correct classifier for the platform you use. // This can be done by enabling the openssl profile. // If the IDE is Eclipse, it requires you to install an additional Eclipse plugin available here: // http://repo1.maven.org/maven2/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // or from your local maven repository: // ~/.m2/repository/kr/motd/maven/os-maven-plugin/1.6.1/os-maven-plugin-1.6.1.jar // Note that installing this plugin may require you to start with a new workspace provider = getStringProperty(DrillProperties.TLS_PROVIDER, DEFAULT_SSL_PROVIDER); } private boolean getBooleanProperty(String propName) { return (properties != null) && (properties.containsKey(propName)) && (properties.getProperty(propName).compareToIgnoreCase("true") == 0); } private String getStringProperty(String name, String defaultValue) { String value = ""; if ( (properties != null) && (properties.containsKey(name))) { value = properties.getProperty(name); } if (value.isEmpty()) { value = defaultValue; } value = value.trim(); return value; } private int getIntProperty(String name, int defaultValue) { int value = defaultValue; if (properties != null) { String property = properties.getProperty(name); if (property != null && property.length() > 0) { value = Integer.decode(property); } } return value; } public void validateKeyStore() throws DrillException { } @Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient() .sslProvider(getProvider()) .trustManager(tmf) .protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.nettySslContext = sslCtx; return sslCtx; } @Override public SSLContext initJDKSSLContext() throws DrillException { final SSLContext sslCtx; if (!userSslEnabled) { return null; } TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SSLContext.getInstance(protocol); sslCtx.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ") .append(e.getMessage()) .append("]. ") .toString()); } this.jdkSSlContext = sslCtx; return sslCtx; } @Override public SSLEngine createSSLEngine(BufferAllocator allocator, String peerHost, int peerPort) { SSLEngine engine = super.createSSLEngine(allocator, peerHost, peerPort); if (!this.disableHostVerification()) { SSLParameters sslParameters = engine.getSSLParameters(); // only available since Java 7 sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); engine.setSSLParameters(sslParameters); } engine.setUseClientMode(true); try { engine.setEnableSessionCreation(true); } catch (Exception e) { // Openssl implementation may throw this. logger.debug("Session creation not enabled. Exception: {}", e.getMessage()); } return engine; } @Override public boolean isUserSslEnabled() { return userSslEnabled; } @Override public boolean isHttpsEnabled() { return false; } @Override public String getKeyStoreType() { return emptyString; } @Override public String getKeyStorePath() { return emptyString; } @Override public String getKeyStorePassword() { return emptyString; } @Override public String getKeyPassword() { return emptyString; } @Override public String getTrustStoreType() { return trustStoreType; } @Override public boolean hasTrustStorePath() { return !trustStorePath.isEmpty(); } @Override public String getTrustStorePath() { return trustStorePath; } @Override public boolean hasTrustStorePassword() { return !trustStorePassword.isEmpty(); } @Override public String getTrustStorePassword() { return trustStorePassword; } @Override public String getProtocol() { return protocol; } @Override public SslProvider getProvider() { return provider.equalsIgnoreCase("JDK") ? SslProvider.JDK : SslProvider.OPENSSL; } @Override public int getHandshakeTimeout() { return handshakeTimeout; } @Override public Mode getMode() { return Mode.CLIENT; } @Override public boolean disableHostVerification() { return disableHostVerification; } @Override public boolean disableCertificateVerification() { return disableCertificateVerification; } @Override public boolean useSystemTrustStore() { return useSystemTrustStore; } public boolean isSslValid() { return true; } } |
data class | data class, long method | t | t | t | long method | 0 | 14617 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/ssl/SSLConfigClient.java/#L33-L281 | 1 | 2490 | 14617 | minor | |
| 1931 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12454 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 2 | 1931 | 12454 | major | ||
| 3996 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JavadocFormatter { private static final String CODE_RESET = "\033[0m"; private static final String CODE_HIGHLIGHT = "\033[1m"; private static final String CODE_UNDERLINE = "\033[4m"; private final int lineLimit; private final boolean escapeSequencesSupported; /** Construct the formatter. * * @param lineLimit maximum line length * @param escapeSequencesSupported whether escape sequences are supported */ public JavadocFormatter(int lineLimit, boolean escapeSequencesSupported) { this.lineLimit = lineLimit; this.escapeSequencesSupported = escapeSequencesSupported; } private static final int MAX_LINE_LENGTH = 95; private static final int SHORTEST_LINE = 30; private static final int INDENT = 4; /**Format javadoc to plain text. * * @param header element caption that should be used * @param javadoc to format * @return javadoc formatted to plain text */ public String formatJavadoc(String header, String javadoc) { try { StringBuilder result = new StringBuilder(); result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n"); if (javadoc == null) { return result.toString(); } JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null); DocTrees trees = DocTrees.instance(task); DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) { @Override @DefinedBy(Api.COMPILER) public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return "" + javadoc + ""; } }); new FormatJavadocScanner(result, task).scan(docComment, null); addNewLineIfNeeded(result); return result.toString(); } catch (URISyntaxException ex) { throw new InternalError("Unexpected exception", ex); } } private class FormatJavadocScanner extends DocTreeScanner { private final StringBuilder result; private final JavacTask task; private int reflownTo; private int indent; private int limit = Math.min(lineLimit, MAX_LINE_LENGTH); private boolean pre; private Map tableColumns; public FormatJavadocScanner(StringBuilder result, JavacTask task) { this.result = result; this.task = task; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitDocComment(DocCommentTree node, Object p) { tableColumns = countTableColumns(node); reflownTo = result.length(); scan(node.getFirstSentence(), p); scan(node.getBody(), p); reflow(result, reflownTo, indent, limit); for (Sections current : docSections.keySet()) { boolean seenAny = false; for (DocTree t : node.getBlockTags()) { if (current.matches(t)) { if (!seenAny) { seenAny = true; if (result.charAt(result.length() - 1) != '\n') result.append("\n"); result.append("\n"); result.append(escape(CODE_UNDERLINE)) .append(docSections.get(current)) .append(escape(CODE_RESET)) .append("\n"); } scan(t, null); } } } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitText(TextTree node, Object p) { String text = node.getBody(); if (!pre) { text = text.replaceAll("[ \t\r\n]+", " ").trim(); if (text.isEmpty()) { text = " "; } } else { text = text.replaceAll("\n", "\n" + indentString(indent)); } result.append(text); return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLink(LinkTree node, Object p) { if (!node.getLabel().isEmpty()) { scan(node.getLabel(), p); } else { result.append(node.getReference().getSignature()); } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitParam(ParamTree node, Object p) { return formatDef(node.getName().getName(), node.getDescription()); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitThrows(ThrowsTree node, Object p) { return formatDef(node.getExceptionName().getSignature(), node.getDescription()); } public Object formatDef(CharSequence name, List description) { result.append(name); result.append(" - "); reflownTo = result.length(); indent = name.length() + 3; if (limit - indent < SHORTEST_LINE) { result.append("\n"); result.append(indentString(INDENT)); indent = INDENT; reflownTo += INDENT; } try { return scan(description, null); } finally { reflow(result, reflownTo, indent, limit); result.append("\n"); } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitLiteral(LiteralTree node, Object p) { return scan(node.getBody(), p); } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitReturn(ReturnTree node, Object p) { reflownTo = result.length(); try { return super.visitReturn(node, p); } finally { reflow(result, reflownTo, 0, limit); } } Stack listStack = new Stack<>(); Stack defStack = new Stack<>(); Stack tableStack = new Stack<>(); Stack> cellsStack = new Stack<>(); Stack> headerStack = new Stack<>(); @Override @DefinedBy(Api.COMPILER_TREE) public Object visitStartElement(StartElementTree node, Object p) { switch (getHtmlTag(node.getName())) { case P: if (lastNode!= null && lastNode.getKind() == DocTree.Kind.START_ELEMENT && HtmlTag.get(((StartElementTree) lastNode).getName()) == HtmlTag.LI) { //ignore break; } reflowTillNow(); addNewLineIfNeeded(result); result.append(indentString(indent)); reflownTo = result.length(); break; case BLOCKQUOTE: reflowTillNow(); indent += INDENT; break; case PRE: reflowTillNow(); pre = true; break; case UL: reflowTillNow(); listStack.push(-1); indent += INDENT; break; case OL: reflowTillNow(); listStack.push(1); indent += INDENT; break; case DL: reflowTillNow(); defStack.push(indent); break; case LI: reflowTillNow(); if (!listStack.empty()) { addNewLineIfNeeded(result); int top = listStack.pop(); if (top == (-1)) { result.append(indentString(indent - 2)); result.append("* "); } else { result.append(indentString(indent - 3)); result.append("" + top++ + ". "); } listStack.push(top); reflownTo = result.length(); } break; case DT: reflowTillNow(); if (!defStack.isEmpty()) { addNewLineIfNeeded(result); indent = defStack.peek(); result.append(escape(CODE_HIGHLIGHT)); } break; case DD: reflowTillNow(); if (!defStack.isEmpty()) { if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } addNewLineIfNeeded(result); indent = defStack.peek() + INDENT; result.append(indentString(indent)); } break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); addNewLineIfNeeded(result); result.append("\n") .append(escape(CODE_UNDERLINE)); reflownTo = result.length(); break; case TABLE: int columns = tableColumns.get(node); if (columns == 0) { break; //broken input } reflowTillNow(); addNewLineIfNeeded(result); reflownTo = result.length(); tableStack.push(limit); limit = (limit - 1) / columns - 3; for (int sep = 0; sep < (limit + 3) * columns + 1; sep++) { result.append("-"); } result.append("\n"); break; case TR: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(node.getName()); } cellsStack.push(new ArrayList<>()); headerStack.push(new ArrayList<>()); break; case TH: case TD: if (cellsStack.isEmpty()) { //broken code break; } reflowTillNow(); result.append("\n"); reflownTo = result.length(); cellsStack.peek().add(result.length()); headerStack.peek().add(HtmlTag.get(node.getName()) == HtmlTag.TH); break; case IMG: for (DocTree attr : node.getAttributes()) { if (attr.getKind() != DocTree.Kind.ATTRIBUTE) { continue; } AttributeTree at = (AttributeTree) attr; if ("alt".equals(StringUtils.toLowerCase(at.getName().toString()))) { addSpaceIfNeeded(result); scan(at.getValue(), null); addSpaceIfNeeded(result); break; } } break; default: addSpaceIfNeeded(result); break; } return null; } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEndElement(EndElementTree node, Object p) { handleEndElement(node.getName()); return super.visitEndElement(node, p); } private void handleEndElement(Name name) { switch (getHtmlTag(name)) { case BLOCKQUOTE: indent -= INDENT; break; case PRE: pre = false; addNewLineIfNeeded(result); reflownTo = result.length(); break; case UL: case OL: if (listStack.isEmpty()) { //ignore stray closing tag break; } reflowTillNow(); listStack.pop(); indent -= INDENT; addNewLineIfNeeded(result); break; case DL: if (defStack.isEmpty()) {//ignore stray closing tag break; } reflowTillNow(); if (indent == defStack.peek()) { result.append(escape(CODE_RESET)); } indent = defStack.pop(); addNewLineIfNeeded(result); break; case H1: case H2: case H3: case H4: case H5: case H6: reflowTillNow(); result.append(escape(CODE_RESET)) .append("\n"); reflownTo = result.length(); break; case TABLE: if (cellsStack.size() >= tableStack.size()) { //unclosed : handleEndElement(task.getElements().getName("tr")); } if (tableStack.isEmpty()) { break; } limit = tableStack.pop(); break; case TR: if (cellsStack.isEmpty()) { break; } reflowTillNow(); List cells = cellsStack.pop(); List headerFlags = headerStack.pop(); List content = new ArrayList<>(); int maxLines = 0; result.append("\n"); while (!cells.isEmpty()) { int currentCell = cells.remove(cells.size() - 1); String[] lines = result.substring(currentCell, result.length()).split("\n"); result.delete(currentCell - 1, result.length()); content.add(lines); maxLines = Math.max(maxLines, lines.length); } Collections.reverse(content); for (int line = 0; line < maxLines; line++) { for (int column = 0; column < content.size(); column++) { String[] lines = content.get(column); String currentLine = line < lines.length ? lines[line] : ""; result.append("| "); boolean header = headerFlags.get(column); if (header) { result.append(escape(CODE_HIGHLIGHT)); } result.append(currentLine); if (header) { result.append(escape(CODE_RESET)); } int padding = limit - currentLine.length(); if (padding > 0) result.append(indentString(padding)); result.append(" "); } result.append("|\n"); } for (int sep = 0; sep < (limit + 3) * content.size() + 1; sep++) { result.append("-"); } result.append("\n"); reflownTo = result.length(); break; case TD: case TH: break; default: addSpaceIfNeeded(result); break; } } @Override @DefinedBy(Api.COMPILER_TREE) public Object visitEntity(EntityTree node, Object p) { String name = node.getName().toString(); int code = -1; if (name.startsWith("#")) { try { int v = StringUtils.toLowerCase(name).startsWith("#x") ? Integer.parseInt(name.substring(2), 16) : Integer.parseInt(name.substring(1), 10); if (Entity.isValid(v)) { code = v; } } catch (NumberFormatException ex) { //ignore } } else { Entity entity = Entity.get(name); if (entity != null) { code = entity.code; } } if (code != (-1)) { result.appendCodePoint(code); } else { result.append(node.toString()); } return super.visitEntity(node, p); } private DocTree lastNode; @Override @DefinedBy(Api.COMPILER_TREE) public Object scan(DocTree node, Object p) { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } try { return super.scan(node, p); } finally { if (node instanceof InlineTagTree) { addSpaceIfNeeded(result); } lastNode = node; } } private void reflowTillNow() { while (result.length() > 0 && result.charAt(result.length() - 1) == ' ') result.delete(result.length() - 1, result.length()); reflow(result, reflownTo, indent, limit); reflownTo = result.length(); } }; private String escape(String sequence) { return this.escapeSequencesSupported ? sequence : ""; } private static final Map docSections = new LinkedHashMap<>(); static { ResourceBundle bundle = ResourceBundle.getBundle("jdk.internal.shellsupport.doc.resources.javadocformatter"); docSections.put(Sections.TYPE_PARAMS, bundle.getString("CAP_TypeParameters")); docSections.put(Sections.PARAMS, bundle.getString("CAP_Parameters")); docSections.put(Sections.RETURNS, bundle.getString("CAP_Returns")); docSections.put(Sections.THROWS, bundle.getString("CAP_Thrown_Exceptions")); } private static String indentString(int indent) { char[] content = new char[indent]; Arrays.fill(content, ' '); return new String(content); } private static void reflow(StringBuilder text, int from, int indent, int limit) { int lineStart = from; while (lineStart > 0 && text.charAt(lineStart - 1) != '\n') { lineStart--; } int lineChars = from - lineStart; int pointer = from; int lastSpace = -1; while (pointer < text.length()) { if (text.charAt(pointer) == ' ') lastSpace = pointer; if (lineChars >= limit) { if (lastSpace != (-1)) { text.setCharAt(lastSpace, '\n'); text.insert(lastSpace + 1, indentString(indent)); lineChars = indent + pointer - lastSpace - 1; pointer += indent; lastSpace = -1; } } lineChars++; pointer++; } } private static void addNewLineIfNeeded(StringBuilder text) { if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') { text.append("\n"); } } private static void addSpaceIfNeeded(StringBuilder text) { if (text.length() == 0) return ; char last = text.charAt(text.length() - 1); if (last != ' ' && last != '\n') { text.append(" "); } } private static HtmlTag getHtmlTag(Name name) { HtmlTag tag = HtmlTag.get(name); return tag != null ? tag : HtmlTag.HTML; //using HtmlTag.HTML as default no-op value } private static Map countTableColumns(DocCommentTree dct) { Map result = new IdentityHashMap<>(); new DocTreeScanner() { private StartElementTree currentTable; private int currentMaxColumns; private int currentRowColumns; @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { switch (getHtmlTag(node.getName())) { case TABLE: currentTable = node; break; case TR: currentMaxColumns = Math.max(currentMaxColumns, currentRowColumns); currentRowColumns = 0; break; case TD: case TH: currentRowColumns++; break; } return super.visitStartElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitEndElement(EndElementTree node, Void p) { if (HtmlTag.get(node.getName()) == HtmlTag.TABLE) { closeTable(); } return super.visitEndElement(node, p); } @Override @DefinedBy(Api.COMPILER_TREE) public Void visitDocComment(DocCommentTree node, Void p) { try { return super.visitDocComment(node, p); } finally { closeTable(); } } private void closeTable() { if (currentTable != null) { result.put(currentTable, Math.max(currentMaxColumns, currentRowColumns)); currentTable = null; } } }.scan(dct, null); return result; } private enum Sections { TYPE_PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && ((ParamTree) t).isTypeParameter(); } }, PARAMS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.PARAM && !((ParamTree) t).isTypeParameter(); } }, RETURNS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.RETURN; } }, THROWS { @Override public boolean matches(DocTree t) { return t.getKind() == DocTree.Kind.THROWS; } }; public abstract boolean matches(DocTree t); } } |
blob | blob, long method | t | t | t | long method | 0 | 10563 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java/#L70-L712 | 1 | 3996 | 10563 | minor | |
| 1157 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | long method, data class | t | t | t | long method | 0 | 10144 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 1157 | 10144 | critical | |
| 2530 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected Server createJettyServer(JettyHttpHandlerAdapter servlet) { int port = (getPort() >= 0) ? getPort() : 0; InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); server.addConnector(createConnector(address, server)); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler(server, "", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler)); JettyReactiveWebServerFactory.logger .info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return server; } |
long method | long method | t | t | t | 0 | 14736 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactory.java/#L171-L194 | 1 | 2530 | 14736 | minor | ||
| 2346 | YES I found bad smells The bad smells are: 1. Data class 2. Lack of encapsulation 3. Long method 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | Data class2 Lack of encapsulation3 Long method4 Feature envy | t | f | t | 0 | 14193 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 2 | 2346 | 14193 | major | ||
| 667 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractSimpleExtractor implements Extractor { private static final Logger LOG = LoggerFactory.getLogger(AbstractSimpleExtractor.class); private static final int LOG_ERROR_LIMIT = 100; private int errors; private boolean errorOnLast; private final T defaultValue; private final TokenizerFactory scannerFactory; protected AbstractSimpleExtractor(T defaultValue) { this(defaultValue, TokenizerFactory.getDefaultInstance()); } protected AbstractSimpleExtractor(T defaultValue, TokenizerFactory scannerFactory) { this.defaultValue = defaultValue; this.scannerFactory = scannerFactory; } @Override public void initialize() { this.errors = 0; this.errorOnLast = false; } @Override public T extract(String input) { errorOnLast = false; T res = defaultValue; try { res = doExtract(scannerFactory.create(input)); } catch (Exception e) { errorOnLast = true; errors++; if (errors < LOG_ERROR_LIMIT) { LOG.error("Error occurred parsing input '{}' using extractor {}", input, this); } } return res; } @Override public boolean errorOnLastRecord() { return errorOnLast; } @Override public T getDefaultValue() { return defaultValue; } @Override public ExtractorStats getStats() { return new ExtractorStats(errors); } /** * Subclasses must override this method to return a new instance of the * class that this {@code Extractor} instance is designed to parse. * Any runtime parsing exceptions from the given {@code Tokenizer} instance * should be thrown so that they may be caught by the error handling logic * inside of this class. * * @param tokenizer The {@code Tokenizer} instance for the current record * @return A new instance of the type defined for this class */ protected abstract T doExtract(Tokenizer tokenizer); } |
data class | data class, long method | t | t | t | long method | 0 | 6549 | https://github.com/apache/crunch/blob/9b8849cfd89f1e7f187b99914163509060692aa5/crunch-contrib/src/main/java/org/apache/crunch/contrib/text/AbstractSimpleExtractor.java/#L28-L95 | 1 | 667 | 6549 | minor | |
| 2031 | YES I found bad smells The bad smells are: 1. Long method (computeContentSummary) 2. Feature envy (in computeContentSummary and computeQuotaUsage methods) 3. Duplicate code (in computeQuotaUsage method) 4. Data class (INodeReference class has only private fields and getters/setters) 5. Primitive obsession (use of bytes instead of a custom class for names) 6. Refused bequest (overriding methods unnecessarily in WithName class) 7. Null checks and fail-fast behavior (in cleanSubtree and destroyAndCollectBlocks methods) 8. Intensive coupling (reliance on specific methods and classes) 9. Inconsistent naming of methods and variables 10. Use of final keyword unnecessarily. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class WithName extends INodeReference { private final byte[] name; /** * The id of the last snapshot in the src tree when this WithName node was * generated. When calculating the quota usage of the referred node, only * the files/dirs existing when this snapshot was taken will be counted for * this WithName node and propagated along its ancestor path. */ private final int lastSnapshotId; public WithName(INodeDirectory parent, WithCount referred, byte[] name, int lastSnapshotId) { super(parent, referred); this.name = name; this.lastSnapshotId = lastSnapshotId; referred.addReference(this); } @Override public final byte[] getLocalNameBytes() { return name; } @Override public final void setLocalName(byte[] name) { throw new UnsupportedOperationException("Cannot set name: " + getClass() + " is immutable."); } public int getLastSnapshotId() { return lastSnapshotId; } @Override public final ContentSummaryComputationContext computeContentSummary( int snapshotId, ContentSummaryComputationContext summary) { final int s = snapshotId < lastSnapshotId ? snapshotId : lastSnapshotId; // only count storagespace for WithName final QuotaCounts q = computeQuotaUsage( summary.getBlockStoragePolicySuite(), getStoragePolicyID(), false, s); summary.getCounts().addContent(Content.DISKSPACE, q.getStorageSpace()); summary.getCounts().addTypeSpaces(q.getTypeSpaces()); return summary; } @Override public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps, byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) { // if this.lastSnapshotId < lastSnapshotId, the rename of the referred // node happened before the rename of its ancestor. This should be // impossible since for WithName node we only count its children at the // time of the rename. Preconditions.checkState(lastSnapshotId == Snapshot.CURRENT_STATE_ID || this.lastSnapshotId >= lastSnapshotId); final INode referred = this.getReferredINode().asReference() .getReferredINode(); // We will continue the quota usage computation using the same snapshot id // as time line (if the given snapshot id is valid). Also, we cannot use // cache for the referred node since its cached quota may have already // been updated by changes in the current tree. int id = lastSnapshotId != Snapshot.CURRENT_STATE_ID ? lastSnapshotId : this.lastSnapshotId; return referred.computeQuotaUsage(bsps, blockStoragePolicyId, false, id); } @Override public void cleanSubtree(ReclaimContext reclaimContext, final int snapshot, int prior) { // since WithName node resides in deleted list acting as a snapshot copy, // the parameter snapshot must be non-null Preconditions.checkArgument(snapshot != Snapshot.CURRENT_STATE_ID); // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to the // previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } if (prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } // record the old quota delta QuotaCounts old = reclaimContext.quotaDelta().getCountsCopy(); getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { QuotaCounts current = reclaimContext.quotaDelta().getCountsCopy(); current.subtract(old); // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, current); } if (snapshot < lastSnapshotId) { // for a WithName node, when we compute its quota usage, we only count // in all the nodes existing at the time of the corresponding rename op. // Thus if we are deleting a snapshot before/at the snapshot associated // with lastSnapshotId, we do not need to update the quota upwards. reclaimContext.quotaDelta().setCounts(old); } } @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { int snapshot = getSelfSnapshot(); reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(reclaimContext.getCopy()); } else { int prior = getPriorSnapshot(this); INode referred = getReferredINode().asReference().getReferredINode(); if (snapshot != Snapshot.NO_SNAPSHOT_ID) { if (prior != Snapshot.NO_SNAPSHOT_ID && snapshot <= prior) { // the snapshot to be deleted has been deleted while traversing // the src tree of the previous rename operation. This usually // happens when rename's src and dst are under the same // snapshottable directory. E.g., the following operation sequence: // 1. create snapshot s1 on /test // 2. rename /test/foo/bar to /test/foo2/bar // 3. create snapshot s2 on /test // 4. rename foo2 again // 5. delete snapshot s2 return; } ReclaimContext newCtx = reclaimContext.getCopy(); referred.cleanSubtree(newCtx, snapshot, prior); INodeReference ref = getReferredINode().getParentReference(); if (ref != null) { // we need to update the quota usage along the parent path from ref reclaimContext.quotaDelta().addUpdatePath(ref, newCtx.quotaDelta().getCountsCopy()); } } } } private int getSelfSnapshot() { INode referred = getReferredINode().asReference().getReferredINode(); int snapshot = Snapshot.NO_SNAPSHOT_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { snapshot = referred.asFile().getDiffs().getPrior(lastSnapshotId); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { snapshot = sf.getDiffs().getPrior(lastSnapshotId); } } return snapshot; } } |
data class | Long method (computeContentSummary)2 Feature envy (in computeContentSummary and computeQuotaUsage methods)3 Duplicate code (in computeQuotaUsage method)4 Data class (INodeReference class has only private fields and getters/setters)5 Primitive obsession (use of bytes instead of a custom class for names)6 Refused bequest (overriding methods unnecessarily in WithName class)7 Null checks and fail-fast behavior (in cleanSubtree and destroyAndCollectBlocks methods)8 Intensive coupling (reliance on specific methods and classes)9 Inconsistent naming of methods and variables | t | f | t | 0 | 12811 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java/#L466-L619 | 2 | 2031 | 12811 | minor | ||
| 2060 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EObject", propOrder = { "extensions" }) public class EObject { @XmlElement(name = "Extension", namespace = "http://www.omg.org/XMI") protected List extensions; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected QName type; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String version; @XmlAttribute protected String href; @XmlAttribute(namespace = "http://www.omg.org/XMI") @XmlIDREF protected Object idref; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String label; @XmlAttribute(namespace = "http://www.omg.org/XMI") protected String uuid; /** * Gets the value of the extensions property. * * * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * set method for the extensions property. * * * For example, to add a new item, do as follows: * * * getExtensions().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Extension } * * */ public List getExtensions() { if (extensions == null) { extensions = new ArrayList(); } return this.extensions; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return possible object is {@link QName } * */ public QName getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is {@link QName } * */ public void setType(QName value) { this.type = value; } /** * Gets the value of the version property. * * @return possible object is {@link String } * */ public String getVersion() { if (version == null) { return "2.0"; } else { return version; } } /** * Sets the value of the version property. * * @param value * allowed object is {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the href property. * * @return possible object is {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the idref property. * * @return possible object is {@link Object } * */ public Object getIdref() { return idref; } /** * Sets the value of the idref property. * * @param value * allowed object is {@link Object } * */ public void setIdref(Object value) { this.idref = value; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the uuid property. * * @return possible object is {@link String } * */ public String getUuid() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is {@link String } * */ public void setUuid(String value) { this.uuid = value; } } |
data class | data class | t | t | t | 0 | 12964 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-jee/src/main/java/org/apache/openejb/jee/was/v6/ecore/EObject.java/#L57-L262 | 1 | 2060 | 12964 | major | ||
| 923 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 8280 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 923 | 8280 | minor | |
| 4664 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12456 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 2 | 4664 | 12456 | minor | ||
| 1747 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 11855 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1747 | 11855 | minor | |
| 1217 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 10323 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 1217 | 10323 | major | ||
| 781 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
long method | long method, data class | t | t | t | data class | 0 | 7457 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 1 | 781 | 7457 | major | |
| 177 | {"answer":"YES I found bad smells","the bad smells are: 1. Blob, 2. Long Method, 3. Long Parameter List, 4. Data Class, 5. Feature Envy, 6. Long Method, 7. Long Parameter List, 8. Data Class, 9. Feature Envy, 10. Long Method, 11. Long Parameter List, 12. Data Class, 13. Feature Envy, 14. Long Method, 15. Blob, 16. Long Parameter List, 17. Data Class, 18. Feature Envy, 19. Long Method, 20. Blob, 21. Long Parameter List, 22. Data Class, 23. Long Method, 24. Blob, 25. Long Parameter List, 26. Data Class, 27. Feature Envy, 28. Long Method, 29. Blob, 30. Long Parameter List, 31. Data Class, 32. Feature Envy, 33. Long Method, 34. Blob, 35. Long Parameter List, 36. Data Class, 37. Feature Envy, 38. Long Method, 39. Blob, 40. Long Parameter List, 41. Data Class, 42. Feature Envy, 43. Long Method, 44. Blob, 45. Long Parameter List, 46. Data Class, 47. Feature Envy, 48. Long Method, 49. Blob, 50. Long Parameter List, 51. Data Class, 52. Feature Envy, 53. Long Method, 54. Blob, 55. Long Parameter List, 56. Data Class, 57. Feature Envy, 58. Long Method, 59. Long Parameter List, 60. Data Class, 61. Feature Envy, 62. Long Method, 63. Long Parameter List, 64. Data Class, 65. Feature Envy, 66. Long Method, 67. Long Parameter List, 68. Data Class, 69. Feature Envy, 70. Long Method, 71. Blob, 72. Data Class, 73. Long Method, 74. Blob, 75. Data Class, 76. Long Method, 77. Blob, 78. Data Class, 79. Long Method, 80. Blob, 81. Data Class, 82. Long Method, 83. Blob, 84. Data Class, 85. Long Method, 86. Blob, 87. Data Class, 88. Long Method, 89. Blob, 90. Data Class, 91. Long Method, 92. Long Parameter List, 93. Data Class, 94. Feature Envy, 95. Long Method, 96. Long Parameter List, 97. Data Class, 98. Feature Envy, 99. Long Method, 100. Long Parameter List, 101. Data Class, 102. Feature Envy, 103. Long Method, 104. Long Parameter List, 105. Data Class, 106. Feature Envy, 107. Long Method, 108. Long Parameter List, 109. Data Class, 110. Feature Envy, 111. Long Method, 112. Long Parameter List, 113. Data Class, 114. Feature Envy, 115. Long Method, 116. Long Parameter List, 117. Data Class, 118. Feature Envy, 119. Long Method, 120. Long Parameter List, 121. Data Class, 122. Feature Envy, 123. Long Method, 124. Long Parameter List, 125. Data Class, 126. Feature Envy, 127. Long Method, 128. Long Parameter List, 129. Data Class, 130. Feature Envy, 131. Long Method, 132. Long Parameter List, 133. Data Class, 134. Feature Envy, 135. Long Method, 136. Long Parameter List, 137. Data Class, 138. Feature Envy, 139. Long Method, 140. Long Parameter List, 141. Data Class, 142. Feature Envy, 143. Long Method, 144. Long Parameter List, 145. Data Class, 146. Feature Envy, 147. Long Method, 148. Long Parameter List, 149. Data Class, 150. Feature Envy, 151. Long Method, 152. Long Parameter List, 153. Data Class, 154. Feature Envy, 155. Long Method, 156. Long Parameter List, 157. Data Class, 158. Feature Envy, 159. Long Method, 160. Long Parameter List, 161. Data Class, 162. Feature Envy, 163. Long Method, 164. Long Parameter List, 165. Data Class, 166. Feature Envy, 167. Long Method, 168. Long Parameter List, 169. Data Class, 170. Feature Envy, 171. Long Method, 172. Long Parameter List, 173. Data Class, 174. Feature Envy, 175. Blob, 176. Data Class, 177. Feature Envy, 178. Long Method, 179. Blob, 180. Data Class, 181. Feature Envy, 182. Long Method, 183. Blob, 184. Data Class, 185. Feature Envy, 186. Long Method, 187. Blob, 188. Long Parameter List, 189. Data Class, 190. Feature Envy, 191. Long Method, 192. Blob, 193. Long Parameter List, 194. Data Class, 195. Feature Envy, 196. Long Method, 197. Blob, 198. Long Parameter List, 199. Data Class, 200. Feature Envy, 201. Blob, 202. Data Class, 203. Feature Envy, 204. Long Method, 205. Blob, 206. Data Class, 207. Feature Envy, 208. Long Method, 209. Blob, 210. Data Class, 211. Feature Envy, 212. Long Method, 213. Blob, 214. Data Class, 215. Feature Envy, 216. Long Method, 217. Blob, 218. Data Class, 219. Feature Envy, 220. Long Method, 221. Blob, 222. Data Class, 223. Feature Envy, 224. Long Method, 225. Blob, 226. Data Class, 227. Feature Envy, 228. Long Method, 229. Blob, 230. Data Class, 231. Feature Envy, 232. Long Method, 233. Long Parameter List, 234. Data Class, 235. Feature Envy, 236. Long Method, 237. Long Parameter List, 238. Data Class, 239. Feature Envy, 240. Long Method, 241. Long Parameter List, 242. Data Class, 243. Feature Envy, 244. Long Method, 245. Long Parameter List, 246. Data Class, 247. Feature Envy, 248. Long Method, 249. Long Parameter List, 250. Data Class, 251. Feature Envy, 252. Long Method, 253. Long Parameter List, 254. Data Class, 255. Feature Envy, 256. Long Method, 257. Long Parameter List, 258. Data Class, 259. Feature Envy, 260. Long Method, 261. Long Parameter List, 262. Data Class, 263. Feature Envy, 264. Long Method, 265. Long Parameter List, 266. Data Class, 267. Feature Envy, 268. Long Method, 269. Long Parameter List, 270. Data Class, 271. Feature Envy, 272. Long Method, 273. Long Parameter List, 274. Data Class, 275. Feature Envy, 276. Long Method, 277. Long Parameter List, 278. Data Class, 279. Feature Envy, 280. Long Method, 281. Long Parameter List, 282. Data Class, 283. Feature Envy, 284. Long Method, 285. Long Parameter List, 286. Data Class, 287. Feature Envy, 288. Long Method, 289. Long Parameter List, 290. Data Class, 291. Feature Envy, 292. Long Method, 293. Long Parameter List, 294. Data Class, 295. Feature Envy, 296. Long Method, 297. Long Parameter List, 298. Data Class, 299. Feature Envy, 300. Long Method, 301. Long Parameter List, 302. Data Class, 303. Feature Envy, 304. Long Method, 305. Long Parameter List, 306. Data Class, 307. Feature Envy, 308. Long Method, 309. Long Parameter List, 310. Data Class, 311. Feature Envy, 312. Long Method, 313. Long Parameter List, 314. Data Class, 315. Feature Envy, 316. Long Method, 317. Long Parameter List, 318. Data Class, 319. Feature Envy, 320. Long Method, 321. Long Parameter List, 322. Data Class, 323. Feature Envy, 324. Long Method, 325. Long Parameter List, 326. Data Class, 327. Feature Envy, 328. Long Method, 329. Long Parameter List, 330. Data Class, 331. Feature Envy, 332. Long Method, 333. Long Parameter List, 334. Data Class, 335. Feature Envy, 336. Long Method, 337. Long Parameter List, 338. Data Class, 339. Feature Envy, 340. Long Method, 341. Long Parameter List, 342. Data Class, 343. Feature Envy, 344. Long Method, 345. Long Parameter List, 346. Data Class, 347. Feature Envy, 348. Long Method, 349. Long Parameter List, 350. Data Class, 351. Feature Envy, 352. Long Method, 353. Long Parameter List, 354. Data Class, 355. Feature Envy, 356. Long Method, 357. Long Parameter List, 358. Data Class, 359. Feature Envy, 360. Long Method, 361. Long Parameter List, 362. Data Class, 363. Feature Envy, 364. Long Method, 365. Long Parameter List, 366. Data Class, 367. Feature Envy, 368. Long Method, 369. Long Parameter List, 370. Data Class, 371. Feature Envy, 372. Long Method, 373. Long Parameter List, 374. Data Class, 375. Feature Envy, 376. Long Method, 377. Long Parameter List, 378. Data Class, 379. Feature Envy, 380. Long Method, 381. Long Parameter List, 382. Data Class, 383. Feature Envy, 384. Long Method, 385. Long Parameter List, 386. Data Class, 387. Feature Envy, 388. Long Method, 389. Long Parameter List, 390. Data Class, 391. Feature Envy, 392. Long Method, 393. Long Parameter List, 394. Data Class, 395. Feature Envy, 396. Long Method, 397. Long Parameter List, 398. Data Class, 399. Feature Envy, 400. Long Method, 401. Long Parameter List, 402. Data Class, 403. Feature Envy, 404. Long Method, 405. Long Parameter List, 406. Data Class, 407. Feature Envy, 408. Long Method, 409. Long Parameter List, 410. Data Class, 411. Feature Envy, 412. Long Method, 413. Long Parameter List, 414. Data Class, 415. Feature Envy, 416. Long Method, 417. Long Parameter List, 418. Data Class, 419. Feature Envy, 420. Long Method, 421. Long Parameter List, 422. Data Class, 423. Feature Envy, 424. Long Method, 425. Long Parameter List, 426. Data Class, 427. Feature Envy, 428. Long Method, 429. Data Class, 430. Feature Envy, 431. Long Method, 432. Long Parameter List, 433. Data Class, 434. Feature Envy, 435. Long Method, 436. Long Parameter List, 437. Data Class, 438. Feature Envy, 439. Long Method, 440. Long Parameter List, 441. Data Class, 442. Feature Envy, 443. Long Method, 444. Blob, 445. Data Class, 446. Feature Envy, 447. Long Method, 448. Blob, 449. Data Class, 450. Feature Envy, 451. Long Method, 452. Blob, 453. Data Class, 454. Feature Envy, 455. Long Method, 456. Blob, 457. Long Parameter List, 458. Data Class, 459. Feature Envy, 460. Long Method, 461. Blob, 462. Long Parameter List, 463. Data Class, 464. Feature Envy, 465. Long Method, 466. Blob, 467. Long Parameter List, 468. Data Class, 469. Feature Envy, 470. Long Method, 471. Blob, 472. Long Parameter List, 473. Data Class, 474. Feature Envy, 475. Long Method, 476. Data Class, 477. Feature Envy, 478. Long Method, 479. Blob, 480. Data Class, 481. Feature Envy, 482. Long Method, 483. Blob, 484. Data Class, 485. Feature Envy, 486. Long Method, 487. Blob, 488. Data Class, 489. Feature Envy, 490. Long Method, 491. Blob, 492. Data Class, 493. Feature Envy, 494. Long Method, 495. Blob, 496. Data Class, 497. Feature Envy, 498. Long Method, 499. Data Class, 500. Feature Envy, 501. Long Method, 502. Blob, 503. Data Class, 504. Feature Envy, 505. Long Method, 506. Blob, 507. Data Class, 508. Feature Envy, 509. Long Method, 510. Blob, 511. Data Class, 512. Feature Envy, 513. Long Method, 514. Blob, 515. Data Class, 516. Feature Envy, 517. Long Method, 518. Blob, 519. Data Class, 520. Feature Envy, 521. Long Method, 522. Blob, 523. Data Class, 524. Feature Envy, 525. Long Method, 526. Blob, 527. Data Class, 528. Feature Envy, 529. Long Method, 530. Blob, 531. Data Class, 532. Feature Envy, 533. Long Method, 534. Blob, 535. Data Class, 536. Feature Envy, 537. Long Method, 538. Blob, 539. Data Class, 540. Feature Envy, 541. Long Method, 542. Blob, 543. Data Class, 544. Feature Envy, 545. Long Method, 546. Blob, 547. Data Class, 548. Feature Envy, 549. Long Method, 550. Blob, 551. Data Class, 552. Feature Envy, 553. Long Method, 554. Blob, 555. Data Class, 556. Feature Envy, 557. Long Method, 558. Blob, 559. Data Class, 560. Feature Envy, 561. Long Method, 562. Blob, 563. Data Class, 564. Feature Envy, 565. Long Method, 566. Blob, 567. Data Class, 568. Feature Envy, 569. Long Method, 570. Blob, 571. Data Class, 572. Feature Envy, 573. Long Method, 574. Blob, 575. Data Class, 576. Feature Envy, 577. Long Method, 578. Blob, 579. Data Class, 580. Feature Envy, 581. Long Method, 582. Blob, 583. Data Class, 584. Feature Envy, 585. Long Method, 586. Blob, 587. Data Class, 588. Feature Envy, 589. Long Method, 590. Blob, 591. Data Class, 592. Feature Envy, 593. Long Method, 594. Blob, 595. Data Class, 596. Feature Envy, 597. Long Method, 598. Blob, 599. Data Class, 600. Feature Envy, 601. Long Method, 602. Blob, 603. Data Class, 604. Feature Envy, 605. Long Method, 606. Blob, 607. Data Class, 608. Feature Envy, 609. Long Method, 610. Blob, 611. Data Class, 612. Feature Envy, 613. Long Method, 614. Blob, 615. Data Class, 616. Feature Envy, 617. Long Method, 618. Blob, 619. Data Class, 620. Feature Envy, 621. Long Method, 622. Blob, 623. Data Class, 624. Feature Envy, 625. Long Method, 626. Blob, 627. Data Class, 628. Feature Envy, 629. Long Method, 630. Blob, 631. Data Class, 632. Feature Envy, 633. Long Method, 634. Blob, 635. Data Class, 636. Feature Envy, 637. Long Method, 638. Blob, 639. Data Class, 640. Feature Envy, 641. Long Method, 642. Blob, 643. Data Class, 644. Feature Envy, 645. Long Method, 646. Blob, 647. Data Class, 648. Feature Envy, 649. Long Method, 650. Blob, 651. Data Class, 652. Feature Envy, 653 | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | Blob, 2 Long Method, 3 Long Parameter List, 4 Data Class, 5 Feature Envy, 6 Long Method, 7 Long Parameter List, 8 Data Class, 9 Feature Envy, | t | f | t | 2. Long Method, 3. Long Parameter List, 4. Data Class, 5. Feature Envy, 6. Long Method, 7. Long Parameter List, 8. Data Class, 9. Feature Envy, | 0 | 2053 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 177 | 2053 | critical | |
| 48 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Object getApplicationToRun(String[] args) throws CoreException { String configuredApplication = getConfiguredApplication(args); if (configuredApplication == null) { configuredApplication = DEFAULT_APP_3_0; } else { System.out.println("Launching application " + configuredApplication + "..."); } // Assume we are in 3.0 mode. // Find the name of the application as specified by the PDE JUnit launcher. // If no application is specified, the 3.0 default workbench application // is returned. IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME, Platform.PT_APPLICATIONS, configuredApplication); // If no 3.0 extension can be found, search the registry // for the pre-3.0 default workbench application, i.e. org.eclipse ui.workbench // Set the deprecated flag to true if (extension == null) { return null; } // If the extension does not have the correct grammar, return null. // Otherwise, return the application object. IConfigurationElement[] elements = extension.getConfigurationElements(); if (elements.length > 0) { IConfigurationElement[] runs = elements[0].getChildren("run"); //$NON-NLS-1$ if (runs.length > 0) { return runs[0].createExecutableExtension("class"); //$NON-NLS-1$ } } return null; } |
long method | long method | t | t | t | 0 | 854 | https://github.com/eclipse/tycho/blob/913062f90a6bad5c8c2b57c77111a52e698105d5/tycho-surefire/org.eclipse.tycho.surefire.osgibooter/src/main/java/org/eclipse/tycho/surefire/osgibooter/AbstractUITestApplication.java/#L67-L99 | 1 | 48 | 854 | minor | ||
| 4068 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class TemplateConfiguration extends Configurable implements ParserConfiguration { private boolean parentConfigurationSet; private Integer tagSyntax; private Integer interpolationSyntax; private Integer namingConvention; private Boolean whitespaceStripping; private Boolean strictSyntaxMode; private Integer autoEscapingPolicy; private Boolean recognizeStandardFileExtensions; private OutputFormat outputFormat; private String encoding; private Integer tabSize; /** * Creates a new instance. The parent will be {@link Configuration#getDefaultConfiguration()} initially, but it will * be changed to the real parent {@link Configuration} when this object is added to the {@link Configuration}. (It's * not allowed to add the same instance to multiple {@link Configuration}-s). */ public TemplateConfiguration() { super(Configuration.getDefaultConfiguration()); } /** * Same as {@link #setParentConfiguration(Configuration)}. */ @Override void setParent(Configurable cfg) { NullArgumentException.check("cfg", cfg); if (!(cfg instanceof Configuration)) { throw new IllegalArgumentException("The parent of a TemplateConfiguration can only be a Configuration"); } if (parentConfigurationSet) { if (getParent() != cfg) { throw new IllegalStateException( "This TemplateConfiguration is already associated with a different Configuration instance."); } return; } if (((Configuration) cfg).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22 && hasAnyConfigurableSet()) { throw new IllegalStateException( "This TemplateConfiguration can't be associated to a Configuration that has " + "incompatibleImprovements less than 2.3.22, because it changes non-parser settings."); } super.setParent(cfg); parentConfigurationSet = true; } /** * Associates this instance with a {@link Configuration}; usually you don't call this, as it's called internally * when this instance is added to a {@link Configuration}. This method can be called only once (except with the same * {@link Configuration} parameter again, as that changes nothing anyway). * * @throws IllegalArgumentException * if the argument is {@code null} or not a {@link Configuration} * @throws IllegalStateException * if this object is already associated to a different {@link Configuration} object, * or if the {@code Configuration} has {@code #getIncompatibleImprovements()} less than 2.3.22 and * this object tries to change any non-parser settings */ public void setParentConfiguration(Configuration cfg) { setParent(cfg); } /** * Returns the parent {@link Configuration}, or {@code null} if none was associated yet. */ public Configuration getParentConfiguration() { return parentConfigurationSet ? (Configuration) getParent() : null; } private Configuration getNonNullParentConfiguration() { checkParentConfigurationSet(); return (Configuration) getParent(); } /** * Set all settings in this {@link TemplateConfiguration} that were set in the parameter * {@link TemplateConfiguration}, possibly overwriting the earlier value in this object. (A setting is said to be * set in a {@link TemplateConfiguration} if it was explicitly set via a setter method, as opposed to be inherited.) */ public void merge(TemplateConfiguration tc) { if (tc.isAPIBuiltinEnabledSet()) { setAPIBuiltinEnabled(tc.isAPIBuiltinEnabled()); } if (tc.isArithmeticEngineSet()) { setArithmeticEngine(tc.getArithmeticEngine()); } if (tc.isAutoEscapingPolicySet()) { setAutoEscapingPolicy(tc.getAutoEscapingPolicy()); } if (tc.isAutoFlushSet()) { setAutoFlush(tc.getAutoFlush()); } if (tc.isBooleanFormatSet()) { setBooleanFormat(tc.getBooleanFormat()); } if (tc.isClassicCompatibleSet()) { setClassicCompatibleAsInt(tc.getClassicCompatibleAsInt()); } if (tc.isCustomDateFormatsSet()) { setCustomDateFormats(mergeMaps(getCustomDateFormats(), tc.getCustomDateFormats(), false)); } if (tc.isCustomNumberFormatsSet()) { setCustomNumberFormats(mergeMaps(getCustomNumberFormats(), tc.getCustomNumberFormats(), false)); } if (tc.isDateFormatSet()) { setDateFormat(tc.getDateFormat()); } if (tc.isDateTimeFormatSet()) { setDateTimeFormat(tc.getDateTimeFormat()); } if (tc.isEncodingSet()) { setEncoding(tc.getEncoding()); } if (tc.isLocaleSet()) { setLocale(tc.getLocale()); } if (tc.isLogTemplateExceptionsSet()) { setLogTemplateExceptions(tc.getLogTemplateExceptions()); } if (tc.isWrapUncheckedExceptionsSet()) { setWrapUncheckedExceptions(tc.getWrapUncheckedExceptions()); } if (tc.isNamingConventionSet()) { setNamingConvention(tc.getNamingConvention()); } if (tc.isNewBuiltinClassResolverSet()) { setNewBuiltinClassResolver(tc.getNewBuiltinClassResolver()); } if (tc.isTruncateBuiltinAlgorithmSet()) { setTruncateBuiltinAlgorithm(tc.getTruncateBuiltinAlgorithm()); } if (tc.isNumberFormatSet()) { setNumberFormat(tc.getNumberFormat()); } if (tc.isObjectWrapperSet()) { setObjectWrapper(tc.getObjectWrapper()); } if (tc.isOutputEncodingSet()) { setOutputEncoding(tc.getOutputEncoding()); } if (tc.isOutputFormatSet()) { setOutputFormat(tc.getOutputFormat()); } if (tc.isRecognizeStandardFileExtensionsSet()) { setRecognizeStandardFileExtensions(tc.getRecognizeStandardFileExtensions()); } if (tc.isShowErrorTipsSet()) { setShowErrorTips(tc.getShowErrorTips()); } if (tc.isSQLDateAndTimeTimeZoneSet()) { setSQLDateAndTimeTimeZone(tc.getSQLDateAndTimeTimeZone()); } if (tc.isStrictSyntaxModeSet()) { setStrictSyntaxMode(tc.getStrictSyntaxMode()); } if (tc.isTagSyntaxSet()) { setTagSyntax(tc.getTagSyntax()); } if (tc.isInterpolationSyntaxSet()) { setInterpolationSyntax(tc.getInterpolationSyntax()); } if (tc.isTemplateExceptionHandlerSet()) { setTemplateExceptionHandler(tc.getTemplateExceptionHandler()); } if (tc.isAttemptExceptionReporterSet()) { setAttemptExceptionReporter(tc.getAttemptExceptionReporter()); } if (tc.isTimeFormatSet()) { setTimeFormat(tc.getTimeFormat()); } if (tc.isTimeZoneSet()) { setTimeZone(tc.getTimeZone()); } if (tc.isURLEscapingCharsetSet()) { setURLEscapingCharset(tc.getURLEscapingCharset()); } if (tc.isWhitespaceStrippingSet()) { setWhitespaceStripping(tc.getWhitespaceStripping()); } if (tc.isTabSizeSet()) { setTabSize(tc.getTabSize()); } if (tc.isLazyImportsSet()) { setLazyImports(tc.getLazyImports()); } if (tc.isLazyAutoImportsSet()) { setLazyAutoImports(tc.getLazyAutoImports()); } if (tc.isAutoImportsSet()) { setAutoImports(mergeMaps(getAutoImportsWithoutFallback(), tc.getAutoImportsWithoutFallback(), true)); } if (tc.isAutoIncludesSet()) { setAutoIncludes(mergeLists(getAutoIncludesWithoutFallback(), tc.getAutoIncludesWithoutFallback())); } tc.copyDirectCustomAttributes(this, true); } /** * Sets those settings of the {@link Template} which aren't yet set in the {@link Template} and are set in this * {@link TemplateConfiguration}, leaves the other settings as is. A setting is said to be set in a * {@link TemplateConfiguration} or {@link Template} if it was explicitly set via a setter method on that object, as * opposed to be inherited from the {@link Configuration}. * * * Note that this method doesn't deal with settings that influence the parser, as those are already baked in at this * point via the {@link ParserConfiguration}. * * * Note that the {@code encoding} setting of the {@link Template} counts as unset if it's {@code null}, * even if {@code null} was set via {@link Template#setEncoding(String)}. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public void apply(Template template) { Configuration cfg = getNonNullParentConfiguration(); if (template.getConfiguration() != cfg) { // This is actually not a problem right now, but for future BC we enforce this. throw new IllegalArgumentException( "The argument Template doesn't belong to the same Configuration as the TemplateConfiguration"); } if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) { template.setAPIBuiltinEnabled(isAPIBuiltinEnabled()); } if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) { template.setArithmeticEngine(getArithmeticEngine()); } if (isAutoFlushSet() && !template.isAutoFlushSet()) { template.setAutoFlush(getAutoFlush()); } if (isBooleanFormatSet() && !template.isBooleanFormatSet()) { template.setBooleanFormat(getBooleanFormat()); } if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) { template.setClassicCompatibleAsInt(getClassicCompatibleAsInt()); } if (isCustomDateFormatsSet()) { template.setCustomDateFormats( mergeMaps(getCustomDateFormats(), template.getCustomDateFormatsWithoutFallback(), false)); } if (isCustomNumberFormatsSet()) { template.setCustomNumberFormats( mergeMaps(getCustomNumberFormats(), template.getCustomNumberFormatsWithoutFallback(), false)); } if (isDateFormatSet() && !template.isDateFormatSet()) { template.setDateFormat(getDateFormat()); } if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) { template.setDateTimeFormat(getDateTimeFormat()); } if (isEncodingSet() && template.getEncoding() == null) { template.setEncoding(getEncoding()); } if (isLocaleSet() && !template.isLocaleSet()) { template.setLocale(getLocale()); } if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) { template.setLogTemplateExceptions(getLogTemplateExceptions()); } if (isWrapUncheckedExceptionsSet() && !template.isWrapUncheckedExceptionsSet()) { template.setWrapUncheckedExceptions(getWrapUncheckedExceptions()); } if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) { template.setNewBuiltinClassResolver(getNewBuiltinClassResolver()); } if (isTruncateBuiltinAlgorithmSet() && !template.isTruncateBuiltinAlgorithmSet()) { template.setTruncateBuiltinAlgorithm(getTruncateBuiltinAlgorithm()); } if (isNumberFormatSet() && !template.isNumberFormatSet()) { template.setNumberFormat(getNumberFormat()); } if (isObjectWrapperSet() && !template.isObjectWrapperSet()) { template.setObjectWrapper(getObjectWrapper()); } if (isOutputEncodingSet() && !template.isOutputEncodingSet()) { template.setOutputEncoding(getOutputEncoding()); } if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) { template.setShowErrorTips(getShowErrorTips()); } if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) { template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone()); } if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) { template.setTemplateExceptionHandler(getTemplateExceptionHandler()); } if (isAttemptExceptionReporterSet() && !template.isAttemptExceptionReporterSet()) { template.setAttemptExceptionReporter(getAttemptExceptionReporter()); } if (isTimeFormatSet() && !template.isTimeFormatSet()) { template.setTimeFormat(getTimeFormat()); } if (isTimeZoneSet() && !template.isTimeZoneSet()) { template.setTimeZone(getTimeZone()); } if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) { template.setURLEscapingCharset(getURLEscapingCharset()); } if (isLazyImportsSet() && !template.isLazyImportsSet()) { template.setLazyImports(getLazyImports()); } if (isLazyAutoImportsSet() && !template.isLazyAutoImportsSet()) { template.setLazyAutoImports(getLazyAutoImports()); } if (isAutoImportsSet()) { // Regarding the order of the maps in the merge: // - Existing template-level imports have precedence over those coming from the TC (just as with the others // apply()-ed settings), thus for clashing import prefixes they must win. // - Template-level imports count as more specific, and so come after the more generic ones from TC. template.setAutoImports(mergeMaps(getAutoImports(), template.getAutoImportsWithoutFallback(), true)); } if (isAutoIncludesSet()) { template.setAutoIncludes(mergeLists(getAutoIncludes(), template.getAutoIncludesWithoutFallback())); } copyDirectCustomAttributes(template, false); } /** * See {@link Configuration#setTagSyntax(int)}. */ public void setTagSyntax(int tagSyntax) { _TemplateAPI.valideTagSyntaxValue(tagSyntax); this.tagSyntax = Integer.valueOf(tagSyntax); } /** * The getter pair of {@link #setTagSyntax(int)}. */ public int getTagSyntax() { return tagSyntax != null ? tagSyntax.intValue() : getNonNullParentConfiguration().getTagSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isTagSyntaxSet() { return tagSyntax != null; } /** * See {@link Configuration#setInterpolationSyntax(int)}. */ public void setInterpolationSyntax(int interpolationSyntax) { _TemplateAPI.valideInterpolationSyntaxValue(interpolationSyntax); this.interpolationSyntax = Integer.valueOf(interpolationSyntax); } /** * The getter pair of {@link #setInterpolationSyntax(int)}. */ public int getInterpolationSyntax() { return interpolationSyntax != null ? interpolationSyntax.intValue() : getNonNullParentConfiguration().getInterpolationSyntax(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isInterpolationSyntaxSet() { return interpolationSyntax != null; } /** * See {@link Configuration#setNamingConvention(int)}. */ public void setNamingConvention(int namingConvention) { _TemplateAPI.validateNamingConventionValue(namingConvention); this.namingConvention = Integer.valueOf(namingConvention); } /** * The getter pair of {@link #setNamingConvention(int)}. */ public int getNamingConvention() { return namingConvention != null ? namingConvention.intValue() : getNonNullParentConfiguration().getNamingConvention(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isNamingConventionSet() { return namingConvention != null; } /** * See {@link Configuration#setWhitespaceStripping(boolean)}. */ public void setWhitespaceStripping(boolean whitespaceStripping) { this.whitespaceStripping = Boolean.valueOf(whitespaceStripping); } /** * The getter pair of {@link #getWhitespaceStripping()}. */ public boolean getWhitespaceStripping() { return whitespaceStripping != null ? whitespaceStripping.booleanValue() : getNonNullParentConfiguration().getWhitespaceStripping(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isWhitespaceStrippingSet() { return whitespaceStripping != null; } /** * Sets the output format of the template; see {@link Configuration#setAutoEscapingPolicy(int)} for more. */ public void setAutoEscapingPolicy(int autoEscapingPolicy) { _TemplateAPI.validateAutoEscapingPolicyValue(autoEscapingPolicy); this.autoEscapingPolicy = Integer.valueOf(autoEscapingPolicy); } /** * The getter pair of {@link #setAutoEscapingPolicy(int)}. */ public int getAutoEscapingPolicy() { return autoEscapingPolicy != null ? autoEscapingPolicy.intValue() : getNonNullParentConfiguration().getAutoEscapingPolicy(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isAutoEscapingPolicySet() { return autoEscapingPolicy != null; } /** * Sets the output format of the template; see {@link Configuration#setOutputFormat(OutputFormat)} for more. */ public void setOutputFormat(OutputFormat outputFormat) { NullArgumentException.check("outputFormat", outputFormat); this.outputFormat = outputFormat; } /** * The getter pair of {@link #setOutputFormat(OutputFormat)}. */ public OutputFormat getOutputFormat() { return outputFormat != null ? outputFormat : getNonNullParentConfiguration().getOutputFormat(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isOutputFormatSet() { return outputFormat != null; } /** * See {@link Configuration#setRecognizeStandardFileExtensions(boolean)}. */ public void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions) { this.recognizeStandardFileExtensions = Boolean.valueOf(recognizeStandardFileExtensions); } /** * Getter pair of {@link #setRecognizeStandardFileExtensions(boolean)}. */ public boolean getRecognizeStandardFileExtensions() { return recognizeStandardFileExtensions != null ? recognizeStandardFileExtensions.booleanValue() : getNonNullParentConfiguration().getRecognizeStandardFileExtensions(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isRecognizeStandardFileExtensionsSet() { return recognizeStandardFileExtensions != null; } /** * See {@link Configuration#setStrictSyntaxMode(boolean)}. */ public void setStrictSyntaxMode(boolean strictSyntaxMode) { this.strictSyntaxMode = Boolean.valueOf(strictSyntaxMode); } /** * The getter pair of {@link #setStrictSyntaxMode(boolean)}. */ public boolean getStrictSyntaxMode() { return strictSyntaxMode != null ? strictSyntaxMode.booleanValue() : getNonNullParentConfiguration().getStrictSyntaxMode(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. */ public boolean isStrictSyntaxModeSet() { return strictSyntaxMode != null; } @Override public void setStrictBeanModels(boolean strict) { throw new UnsupportedOperationException( "Setting strictBeanModels on " + TemplateConfiguration.class.getSimpleName() + " level isn't supported."); } public String getEncoding() { return encoding != null ? encoding : getNonNullParentConfiguration().getDefaultEncoding(); } /** * When the standard template loading/caching mechanism is used, this forces the charset used for reading the * template "file", overriding everything but the encoding coming from the {@code #ftl} header. This setting * overrides the locale-specific encodings set via {@link Configuration#setEncoding(java.util.Locale, String)}. It * also overrides the {@code encoding} parameter of {@link Configuration#getTemplate(String, String)} (and of its * overloads) and the {@code encoding} parameter of the {@code #include} directive. This works like that because * specifying the encoding where you are requesting the template is error prone and deprecated. * * * If you are developing your own template loading/caching mechanism instead of the standard one, note that the * above behavior is not guaranteed by this class alone; you have to ensure it. Also, read the note on * {@code encoding} in the documentation of {@link #apply(Template)}. */ public void setEncoding(String encoding) { NullArgumentException.check("encoding", encoding); this.encoding = encoding; } public boolean isEncodingSet() { return encoding != null; } /** * See {@link Configuration#setTabSize(int)}. * * @since 2.3.25 */ public void setTabSize(int tabSize) { this.tabSize = Integer.valueOf(tabSize); } /** * Getter pair of {@link #setTabSize(int)}. * * @since 2.3.25 */ public int getTabSize() { return tabSize != null ? tabSize.intValue() : getNonNullParentConfiguration().getTabSize(); } /** * Tells if this setting is set directly in this object or its value is coming from the {@link #getParent() parent}. * * @since 2.3.25 */ public boolean isTabSizeSet() { return tabSize != null; } /** * Returns {@link Configuration#getIncompatibleImprovements()} from the parent {@link Configuration}. This mostly * just exist to satisfy the {@link ParserConfiguration} interface. * * @throws IllegalStateException * If the parent configuration wasn't yet set. */ public Version getIncompatibleImprovements() { return getNonNullParentConfiguration().getIncompatibleImprovements(); } private void checkParentConfigurationSet() { if (!parentConfigurationSet) { throw new IllegalStateException("The TemplateConfiguration wasn't associated with a Configuration yet."); } } private boolean hasAnyConfigurableSet() { return isAPIBuiltinEnabledSet() || isArithmeticEngineSet() || isAutoFlushSet() || isAutoImportsSet() || isAutoIncludesSet() || isBooleanFormatSet() || isClassicCompatibleSet() || isCustomDateFormatsSet() || isCustomNumberFormatsSet() || isDateFormatSet() || isDateTimeFormatSet() || isLazyImportsSet() || isLazyAutoImportsSet() || isLocaleSet() || isLogTemplateExceptionsSet() || isWrapUncheckedExceptionsSet() || isNewBuiltinClassResolverSet() || isTruncateBuiltinAlgorithmSet() || isNumberFormatSet() || isObjectWrapperSet() || isOutputEncodingSet() || isShowErrorTipsSet() || isSQLDateAndTimeTimeZoneSet() || isTemplateExceptionHandlerSet() || isAttemptExceptionReporterSet() || isTimeFormatSet() || isTimeZoneSet() || isURLEscapingCharsetSet(); } private Map mergeMaps(Map m1, Map m2, boolean overwriteUpdatesOrder) { if (m1 == null) return m2; if (m2 == null) return m1; if (m1.isEmpty()) return m2; if (m2.isEmpty()) return m1; LinkedHashMap mergedM = new LinkedHashMap((m1.size() + m2.size()) * 4 / 3 + 1, 0.75f); mergedM.putAll(m1); for (Object m2Key : m2.keySet()) { mergedM.remove(m2Key); // So that duplicate keys are moved after m1 keys } mergedM.putAll(m2); return mergedM; } private List mergeLists(List list1, List list2) { if (list1 == null) return list2; if (list2 == null) return list1; if (list1.isEmpty()) return list2; if (list2.isEmpty()) return list1; ArrayList mergedList = new ArrayList(list1.size() + list2.size()); mergedList.addAll(list1); mergedList.addAll(list2); return mergedList; } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 10741 | https://github.com/apache/freemarker/blob/02fa5edb3cde53f284551c09ecc13301b0e83d0b/src/main/java/freemarker/core/TemplateConfiguration.java/#L77-L718 | 1 | 4068 | 10741 | minor | |
| 476 | {"output": "YES, I found bad smells. The bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | 1. data class | t | t | f | data class | 0 | 4588 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 1 | 476 | 4588 | minor | |
| 953 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8529 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 953 | 8529 | minor | ||
| 1277 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ByteBuffer toByteBuffer(Serializable serializable) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ObjectOutputStream(outputStream).writeObject(serializable); return ByteBuffer.wrap(outputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10590 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/server/mailrepository/mailrepository-cassandra/src/main/java/org/apache/james/mailrepository/cassandra/CassandraMailRepositoryMailDAO.java/#L257-L265 | 2 | 1277 | 10590 | critical | ||
| 2376 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14325 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 2376 | 14325 | minor | ||
| 1615 | YES I found bad smells The bad smells are: 1. Duplicate code 2. Long method 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | Duplicate code 2 Long method 3 Feature envy | t | f | t | 0 | 11472 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 1615 | 11472 | minor | ||
| 316 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) { ContentSearchOptions contentSearchOptions = getContentSearchOptions(session); contentSearchOptions.resultSortOrder = resultSortOrder; contentSearchOptions.changed = true; } |
feature envy | Feature envy | t | f | t | 0 | 3247 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentSearchSession.java/#L90-L94 | 2 | 316 | 3247 | critical | ||
| 789 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Blob", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class DAOAttachment { private final AttachmentId attachmentId; private final BlobId blobId; private final String type; private final long size; private DAOAttachment(AttachmentId attachmentId, BlobId blobId, String type, long size) { this.attachmentId = attachmentId; this.blobId = blobId; this.type = type; this.size = size; } public AttachmentId getAttachmentId() { return attachmentId; } public BlobId getBlobId() { return blobId; } public String getType() { return type; } public long getSize() { return size; } public Attachment toAttachment(byte[] data) { return Attachment.builder() .attachmentId(attachmentId) .type(type) .bytes(data) .build(); } @Override public final boolean equals(Object o) { if (o instanceof DAOAttachment) { DAOAttachment that = (DAOAttachment) o; return Objects.equals(this.size, that.size) && Objects.equals(this.attachmentId, that.attachmentId) && Objects.equals(this.blobId, that.blobId) && Objects.equals(this.type, that.type); } return false; } @Override public final int hashCode() { return Objects.hash(attachmentId, blobId, type, size); } } |
data class | 1. blob, 2. data class | t | t | t | 1. blob | 0 | 7520 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/cassandra/src/main/java/org/apache/james/mailbox/cassandra/mail/CassandraAttachmentDAOV2.java/#L50-L104 | 1 | 789 | 7520 | major | |
| 2003 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Nested loops 4. Use of var instead of specific data types 5. Poor variable names 6. Feature envy 7. Use of deprecated code (such as FSUtils.getRootDir()) 8. Duplicate code (such as using LOG.isTraceEnabled() twice) 9. Use of "continue" statement 10. Complex conditionals (such as if(srcIdx < 0)) 11. Use of hard-coded values (such as Bytes.toBytes()) 12. Catching and throwing generic exceptions (such as IOException) instead of specific ones 13. Use of multiple return statements 14. Inconsistent indentations 15. Use of multiple assignments in one line 16. Use of "else" statements (can be refactored into guard clauses) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") protected Map>[] handleBulkLoad(List sTableList) throws IOException { Map>[] mapForSrc = new Map[sTableList.size()]; List activeFiles = new ArrayList<>(); List archiveFiles = new ArrayList<>(); Pair>>>>, List> pair = backupManager.readBulkloadRows(sTableList); Map>>>> map = pair.getFirst(); FileSystem tgtFs; try { tgtFs = FileSystem.get(new URI(backupInfo.getBackupRootDir()), conf); } catch (URISyntaxException use) { throw new IOException("Unable to get FileSystem", use); } Path rootdir = FSUtils.getRootDir(conf); Path tgtRoot = new Path(new Path(backupInfo.getBackupRootDir()), backupId); for (Map.Entry>>>> tblEntry : map.entrySet()) { TableName srcTable = tblEntry.getKey(); int srcIdx = getIndex(srcTable, sTableList); if (srcIdx < 0) { LOG.warn("Couldn't find " + srcTable + " in source table List"); continue; } if (mapForSrc[srcIdx] == null) { mapForSrc[srcIdx] = new TreeMap<>(Bytes.BYTES_COMPARATOR); } Path tblDir = FSUtils.getTableDir(rootdir, srcTable); Path tgtTable = new Path(new Path(tgtRoot, srcTable.getNamespaceAsString()), srcTable.getQualifierAsString()); for (Map.Entry>>> regionEntry : tblEntry.getValue().entrySet()){ String regionName = regionEntry.getKey(); Path regionDir = new Path(tblDir, regionName); // map from family to List of hfiles for (Map.Entry>> famEntry : regionEntry.getValue().entrySet()) { String fam = famEntry.getKey(); Path famDir = new Path(regionDir, fam); List files; if (!mapForSrc[srcIdx].containsKey(Bytes.toBytes(fam))) { files = new ArrayList<>(); mapForSrc[srcIdx].put(Bytes.toBytes(fam), files); } else { files = mapForSrc[srcIdx].get(Bytes.toBytes(fam)); } Path archiveDir = HFileArchiveUtil.getStoreArchivePath(conf, srcTable, regionName, fam); String tblName = srcTable.getQualifierAsString(); Path tgtFam = new Path(new Path(tgtTable, regionName), fam); if (!tgtFs.mkdirs(tgtFam)) { throw new IOException("couldn't create " + tgtFam); } for (Pair fileWithState : famEntry.getValue()) { String file = fileWithState.getFirst(); int idx = file.lastIndexOf("/"); String filename = file; if (idx > 0) { filename = file.substring(idx+1); } Path p = new Path(famDir, filename); Path tgt = new Path(tgtFam, filename); Path archive = new Path(archiveDir, filename); if (fs.exists(p)) { if (LOG.isTraceEnabled()) { LOG.trace("found bulk hfile " + file + " in " + famDir + " for " + tblName); } if (LOG.isTraceEnabled()) { LOG.trace("copying " + p + " to " + tgt); } activeFiles.add(p.toString()); } else if (fs.exists(archive)){ LOG.debug("copying archive " + archive + " to " + tgt); archiveFiles.add(archive.toString()); } files.add(tgt); } } } } copyBulkLoadedFiles(activeFiles, archiveFiles); backupManager.deleteBulkLoadedRows(pair.getSecond()); return mapForSrc; } |
long method | Long method2 Magic numbers3 Nested loops4 Use of var instead of specific data types5 Poor variable names6 Feature envy7 Use of deprecated code (such as FSUtilsgetRootDir())8 Duplicate code (such as using LOGisTraceEnabled() twice)9 Use of "continue" statement | t | f | t | 0 | 12716 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java/#L115-L201 | 2 | 2003 | 12716 | critical | ||
| 472 | {"message": "YES I found bad smells", "bad_smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { private static final long serialVersionUID = 972154225756734130L; private KapuaId accessInfo; private KapuaId roleId; /** * Constructor * * @param scopeId */ public AccessRoleCreatorImpl(KapuaId scopeId) { super(scopeId); } @Override public KapuaId getAccessInfoId() { return accessInfo; } @Override public void setAccessInfoId(KapuaId accessInfo) { this.accessInfo = accessInfo; } @Override public KapuaId getRoleId() { return roleId; } @Override public void setRoleId(KapuaId roleId) { this.roleId = roleId; } } |
data class | data class | t | t | t | 0 | 4574 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java/#L25-L61 | 1 | 472 | 4574 | major | ||
| 2199 | { "answer": "YES I found bad smells", "bad_smells": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
data class | data class, long method | t | t | t | long method | 0 | 13495 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L30526-L31009 | 1 | 2199 | 13495 | major | |
| 2421 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FieldAttributeModel { /** Typescript value of the type of the field */ private final String typeName; /** For Map, List object, need to initialize field first. Like new Field<>() */ private boolean needInitialize; /** Name of the field */ private String fieldName; /** Java Type of the object (used internally) */ private Type type; /** This field type is a List of objects ? */ private boolean isList; /** This field type is a simple primitive */ private boolean isPrimitive; /** This field type is a map */ private boolean isMap; /** This list type is in fact a list of DTOs */ private boolean isListOfDto; /** This map type is a map of DTOs */ private boolean isMapOfDto; /** * The type is a DTO or a list of DTO and then this value is the name of the DTO implementation */ private String dtoImpl; /** type is a DTO object. */ private boolean isDto; /** type is a Enum object. */ private boolean isEnum; /** Map key type */ private String mapKeyType; /** Map value type */ private String mapValueType; /** Dto type for d.ts */ private String dtsType; /** Dto class where this field declared */ private Class declarationClass; /** * Build a new field model based on the name and Java type * * @param fieldName the name of the field * @param type the Java raw type that will allow further analyzes * @param declarationClass */ public FieldAttributeModel(String fieldName, Type type, Class declarationClass) { this.fieldName = fieldName; this.type = type; this.typeName = convertType(type); this.dtsType = convertTypeForDTS(declarationClass, type); this.declarationClass = declarationClass; if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) { this.needInitialize = true; } if (this.type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) this.type; Type rawType = parameterizedType.getRawType(); analyzeParametrizedType(parameterizedType, rawType); } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type) || String.class.equals(this.type)) { this.isPrimitive = true; } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) { this.isDto = true; dtoImpl = this.type.getTypeName() + "Impl"; } else if (this.type instanceof Class && ((Class) this.type).isEnum()) { this.isEnum = true; } } /** * Analyze a complex parametrized type attribute (which can be a list or map for example) * * @param parameterizedType * @param rawType */ protected void analyzeParametrizedType(ParameterizedType parameterizedType, Type rawType) { if (List.class.equals(rawType)) { this.isList = true; if (parameterizedType.getActualTypeArguments()[0] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[0]) .isAnnotationPresent(DTO.class)) { isListOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[0]) + "Impl"; } } else if (Map.class.equals(rawType)) { isMap = true; mapKeyType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[0]); if (parameterizedType.getActualTypeArguments()[1] instanceof Class && ((Class) parameterizedType.getActualTypeArguments()[1]) .isAnnotationPresent(DTO.class)) { isMapOfDto = true; dtoImpl = convertType(parameterizedType.getActualTypeArguments()[1]) + "Impl"; } mapValueType = convertTypeForDTS(declarationClass, parameterizedType.getActualTypeArguments()[1]); } } public String getTypeName() { return typeName; } public String getFieldName() { return fieldName; } public Type getType() { return type; } public boolean isList() { return isList; } public boolean isPrimitive() { return isPrimitive; } public boolean isMap() { return isMap; } public boolean isListOfDto() { return isListOfDto; } public boolean isMapOfDto() { return isMapOfDto; } public String getDtoImpl() { return dtoImpl; } public boolean isDto() { return isDto; } public boolean isNeedInitialize() { return needInitialize; } public boolean isEnum() { return isEnum; } public String getName() { return this.fieldName; } public String getSimpleType() { return this.typeName; } public String getMapKeyType() { return mapKeyType; } public String getMapValueType() { return mapValueType; } public String getDtsType() { return dtsType; } } |
data class | long method, data class | t | t | t | long method | 0 | 14434 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/core/che-core-typescript-dto-maven-plugin/src/main/java/org/eclipse/che/plugin/typescript/dto/model/FieldAttributeModel.java/#L29-L214 | 1 | 2421 | 14434 | critical | |
| 761 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | data class | t | t | t | 0 | 7110 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 1 | 761 | 7110 | major | ||
| 2497 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, 10.Excessive comments. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2Magic numbers, 3Unnecessary variables, 4Poorly named variables, 5Inconsistent coding style, 6Possible null pointer exception, 7Duplicate code, 8Hard-coded values, 9No exception handling, | t | f | t | 2.Magic numbers, 3.Unnecessary variables, 4.Poorly named variables, 5.Inconsistent coding style, 6.Possible null pointer exception, 7.Duplicate code, 8.Hard-coded values, 9.No exception handling, | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 2497 | 14646 | minor | |
| 345 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doSmapText(Node n) { String text = n.getText(); int index = 0; int next = 0; int lineCount = 1; int skippedLines = 0; boolean slashStarSeen = false; boolean beginning = true; // Count lines inside text, but skipping comment lines at the // beginning of the text. while ((next = text.indexOf('\n', index)) > -1) { if (beginning) { String line = text.substring(index, next).trim(); if (!slashStarSeen && line.startsWith("/*")) { slashStarSeen = true; } if (slashStarSeen) { skippedLines++; int endIndex = line.indexOf("*/"); if (endIndex >= 0) { // End of /* */ comment slashStarSeen = false; if (endIndex < line.length() - 2) { // Some executable code after comment skippedLines--; beginning = false; } } } else if (line.length() == 0 || line.startsWith("//")) { skippedLines++; } else { beginning = false; } } lineCount++; index = next + 1; } doSmap(n, lineCount, 1, skippedLines); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3519 | https://github.com/apache/struts/blob/e82c5a207f62fdb1bb6e8da690325b5a109c924f/plugins/embeddedjsp/src/main/java/org/apache/struts2/jasper/compiler/SmapUtil.java/#L664-L704 | 2 | 345 | 3519 | minor | ||
| 353 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2Magic numbers, 3Duplicated code, 4Nested try/catch blocks, 5Unused parameters, 6Inconsistent naming conventions, 7Hardcoded class names | t | f | t | 2.Magic numbers, 3.Duplicated code, 4.Nested try/catch blocks, 5.Unused parameters, 6.Inconsistent naming conventions, 7.Hardcoded class names | 0 | 3634 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 353 | 3634 | major | |
| 1800 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Inconsistent indentations 4. Magic numbers 5. Nested if statements 6. Complex boolean expressions 7. Hard-to-understand variable names 8. Unused variables | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long method 2 Duplicate code 3 Inconsistent indentations 4 Magic numbers 5 Nested if statements 6 Complex boolean expressions 7 Hard-to-understand variable names 8 Unused variables | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 2 | 1800 | 12011 | minor | ||
| 1892 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method, 2Magic Number, 3Duplicated code, 4Data clumps, 5Conditional complexity | t | f | t | 2.Magic Number, 3.Duplicated code, 4.Data clumps, 5.Conditional complexity | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 1892 | 12318 | major | |
| 1095 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 9781 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 2 | 1095 | 9781 | major | |
| 3964 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | long method | t | t | t | 0 | 10391 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 1 | 3964 | 10391 | major | ||
| 2058 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class CFRouteImpl implements CFRoute { final private String domain; final private String host; final private String path; final private int port; final private String fullRoute; CFRouteImpl(String domain, String host, String path, int port, String fullRoute) { super(); this.domain = domain; this.host = host; this.path = path; this.port = port; this.fullRoute = fullRoute; } public String getDomain() { return domain; } public String getHost() { return host; } public String getPath() { return path; } public int getPort() { return port; } public String getRoute() { return fullRoute; } @Override public String toString() { return "CFRoute [domain=" + domain + ", host=" + host + ", path=" + path + ", port=" + port +"]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((domain == null) ? 0 : domain.hashCode()); result = prime * result + ((fullRoute == null) ? 0 : fullRoute.hashCode()); result = prime * result + ((host == null) ? 0 : host.hashCode()); result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CFRouteImpl other = (CFRouteImpl) obj; if (domain == null) { if (other.domain != null) return false; } else if (!domain.equals(other.domain)) return false; if (fullRoute == null) { if (other.fullRoute != null) return false; } else if (!fullRoute.equals(other.fullRoute)) return false; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (port != other.port) return false; return true; } } |
data class | data class | t | t | t | 0 | 12960 | https://github.com/spring-projects/sts4/blob/46e9e985b0c5e28ea1952d9fc640ec12fd9c8fdd/headless-services/commons/commons-cf/src/main/java/org/springframework/ide/vscode/commons/cloudfoundry/client/CFRouteImpl.java/#L3-L92 | 1 | 2058 | 12960 | major | ||
| 3937 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 3937 | 10309 | major | ||
| 3933 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10289 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 3933 | 10289 | major | |
| 2886 | {"response":"YES I found bad smells","the bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
data class | data class | t | t | t | 0 | 2054 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 2886 | 2054 | major | ||
| 4205 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | long method | t | t | t | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 1 | 4205 | 11065 | minor | ||
| 829 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Use of magic numbers for reader state checks 4. Use of super keyword without clear purpose/reasoning 5. Inconsistent formatting and indentation 6. Complex logic and potential for errors with multiple return statements and conditional checks within the method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Switch statement3 Use of magic numbers for reader state checks4 Use of super keyword without clear purpose/reasoning5 Inconsistent formatting and indentation6 Complex logic and potential for errors with multiple return statements and conditional checks within the method | t | f | t | 0 | 7728 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 829 | 7728 | major | ||
| 1239 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | long method, blob | t | t | t | blob | 0 | 10404 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 1 | 1239 | 10404 | major | |
| 2236 | { "answer": "YES I found bad smells, the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } sb.append(XMLHelper.escape(conf)); } if (prefix.endsWith("\"")) { sb.append("\""); } return sb.toString(); } /** * Writes the extra attributes of the given {@link ExtendableItem} to the given * PrintWriter. * * @param item * the {@link ExtendableItem}, cannot be null * @param out * the writer to use * @param prefix * the string to write before writing the attributes (if any) |
long method | 1. long method | t | t | t | 0 | 13611 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/plugins/parser/xml/XmlModuleDescriptorWriter.java/#L209-L227 | 1 | 2236 | 13611 | minor | ||
| 1829 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 1829 | 12118 | major | |
| 1484 | YES I found bad smells the bad smells are: Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
long method | Long method | t | f | t | 0 | 11088 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 1484 | 11088 | major | ||
| 491 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void initializeOp(Configuration hconf) throws HiveException { // If there is a sort-merge join followed by a regular join, the SMBJoinOperator may not // get initialized at all. Consider the following query: // A SMB B JOIN C // For the mapper processing C, The SMJ is not initialized, no need to close it either. initDone = true; super.initializeOp(hconf); closeCalled = false; this.firstFetchHappened = false; this.inputFileChanged = false; // get the largest table alias from order int maxAlias = 0; for (byte pos = 0; pos < order.length; pos++) { if (pos > maxAlias) { maxAlias = pos; } } maxAlias += 1; nextGroupStorage = new RowContainer[maxAlias]; candidateStorage = new RowContainer[maxAlias]; keyWritables = new ArrayList[maxAlias]; nextKeyWritables = new ArrayList[maxAlias]; fetchDone = new boolean[maxAlias]; foundNextKeyGroup = new boolean[maxAlias]; int bucketSize; // For backwards compatibility reasons we honor the older // HIVEMAPJOINBUCKETCACHESIZE if set different from default. // By hive 0.13 we should remove this code. int oldVar = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEMAPJOINBUCKETCACHESIZE); if (oldVar != 100) { bucketSize = oldVar; } else { bucketSize = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVESMBJOINCACHEROWS); } for (byte pos = 0; pos < order.length; pos++) { RowContainer> rc = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); nextGroupStorage[pos] = rc; RowContainer> candidateRC = JoinUtil.getRowContainer(hconf, rowContainerStandardObjectInspectors[pos], pos, bucketSize,spillTableDesc, conf, !hasFilter(pos), reporter); candidateStorage[pos] = candidateRC; } tagToAlias = conf.convertToArray(conf.getTagToAlias(), String.class); for (byte pos = 0; pos < order.length; pos++) { if (pos != posBigTable) { fetchDone[pos] = false; } foundNextKeyGroup[pos] = false; } } |
long method | Long method2 Feature envy | t | f | t | 0 | 4899 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/SMBMapJoinOperator.java/#L102-L166 | 2 | 491 | 4899 | major | ||
| 1252 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
data class | data class, long method | t | t | t | long method | 0 | 10442 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 1252 | 10442 | minor | |
| 196 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MissedUpdatesFinder extends MissedUpdatesFinderBase { private long ourHighThreshold; // 80th percentile private long ourHighest; // currently just used for logging/debugging purposes private String logPrefix; private long nUpdates; MissedUpdatesFinder(List ourUpdates, String logPrefix, long nUpdates, long ourLowThreshold, long ourHighThreshold) { super(ourUpdates, ourLowThreshold); this.logPrefix = logPrefix; this.ourHighThreshold = ourHighThreshold; this.ourHighest = ourUpdates.get(0); this.nUpdates = nUpdates; } public MissedUpdatesRequest find(List otherVersions, Object updateFrom, Supplier canHandleVersionRanges) { otherVersions.sort(absComparator); if (debug) { log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom); } long otherHigh = percentile(otherVersions, .2f); long otherLow = percentile(otherVersions, .8f); long otherHighest = otherVersions.get(0); if (ourHighThreshold < otherLow) { // Small overlap between version windows and ours is older // This means that we might miss updates if we attempted to use this method. // Since there exists just one replica that is so much newer, we must // fail the sync. log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (ourLowThreshold > otherHigh && ourHighest >= otherHighest) { // Small overlap between windows and ours is newer. // Using this list to sync would result in requesting/replaying results we don't need // and possibly bringing deleted docs back to life. log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); // Because our versions are newer, IndexFingerprint with the remote would not match us. // We return true on our side, but the remote peersync with us should fail. return MissedUpdatesRequest.ALREADY_IN_SYNC; } boolean completeList = otherVersions.size() < nUpdates; MissedUpdatesRequest updatesRequest; if (canHandleVersionRanges.get()) { updatesRequest = handleVersionsWithRanges(otherVersions, completeList); } else { updatesRequest = handleIndividualVersions(otherVersions, completeList); } if (updatesRequest.totalRequestedUpdates > nUpdates) { log.info("{} PeerSync will fail because number of missed updates is more than:{}", logPrefix, nUpdates); return MissedUpdatesRequest.UNABLE_TO_SYNC; } if (updatesRequest == MissedUpdatesRequest.EMPTY) { log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}", logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest); } return updatesRequest; } } |
blob | blob, long method | t | t | t | long method | 0 | 2236 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/PeerSync.java/#L787-L856 | 1 | 196 | 2236 | minor | |
| 1600 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WebServer { public static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private HttpServer2 httpServer; private final HasConfig conf; private InetSocketAddress httpAddress; private InetSocketAddress httpsAddress; protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver"; public WebServer(HasConfig conf) { this.conf = conf; } public HasConfig getConf() { return conf; } private void init() { final String pathSpec = "/has/v1/*"; // add has packages httpServer.addJerseyResourcePackage(AsRequestApi.class .getPackage().getName(), pathSpec); } public void defineFilter() { String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType.equals("kerberos")) { // add authentication filter for webhdfs final String className = conf.getString( WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY, WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT); final String name = className; Map params = getAuthFilterParams(conf); String kadminPathSpec = "/has/v1/kadmin/*"; String hadminPathSpec = "/has/v1/hadmin/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className, params, new String[]{kadminPathSpec, hadminPathSpec}); HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className + ")"); } } public void defineConfFilter() { String confFilterName = ConfFilter.class.getName(); String confPath = "/has/v1/conf/*"; HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName, getAuthFilterParams(conf), new String[]{confPath}); HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName + ")"); } private Map getAuthFilterParams(HasConfig conf) { Map params = new HashMap<>(); String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE); if (authType != null && !authType.isEmpty()) { params.put(AuthenticationFilter.AUTH_TYPE, authType); } String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY); if (principal != null && !principal.isEmpty()) { try { principal = SecurityUtil.getServerPrincipal(principal, getHttpsAddress().getHostName()); } catch (IOException e) { LOG.warn("Errors occurred when get server principal. " + e.getMessage()); } params.put(KerberosAuthenticationHandler.PRINCIPAL, principal); } String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY); if (keytab != null && !keytab.isEmpty()) { params.put(KerberosAuthenticationHandler.KEYTAB, keytab); } String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES); if (rule != null && !rule.isEmpty()) { params.put(KerberosAuthenticationHandler.NAME_RULES, rule); } else { params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT"); } return params; } public InetSocketAddress getBindAddress() { if (httpAddress != null) { return httpAddress; } else if (httpsAddress != null) { return httpsAddress; } else { return null; } } /** * for information related to the different configuration options and * Http Policy is decided. * * @throws HasException HAS exception when starting web server */ public void start() throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); final String bindHost = conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY); InetSocketAddress httpAddr = null; if (policy.isHttpEnabled()) { final String httpAddrString = conf.getString( WebConfigKey.HAS_HTTP_ADDRESS_KEY, WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT); httpAddr = NetUtils.createSocketAddr(httpAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort()); } LOG.info("Get the http address: " + httpAddr); } InetSocketAddress httpsAddr = null; if (policy.isHttpsEnabled()) { final String httpsAddrString = conf.getString( WebConfigKey.HAS_HTTPS_ADDRESS_KEY, WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT); httpsAddr = NetUtils.createSocketAddr(httpsAddrString); if (bindHost != null && !bindHost.isEmpty()) { httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort()); } LOG.info("Get the https address: " + httpsAddr); } HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has"); try { httpServer = builder.build(); } catch (IOException e) { throw new HasException("Errors occurred when building http server. " + e.getMessage()); } init(); try { httpServer.start(); } catch (IOException e) { throw new HasException("Errors occurred when starting http server. " + e.getMessage()); } int connIdx = 0; if (policy.isHttpEnabled()) { httpAddress = httpServer.getConnectorAddress(connIdx++); if (httpAddress != null) { conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, NetUtils.getHostPortString(httpAddress)); } } if (policy.isHttpsEnabled()) { httpsAddress = httpServer.getConnectorAddress(connIdx); if (httpsAddress != null) { conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, NetUtils.getHostPortString(httpsAddress)); } } } public void setWebServerAttribute(HasServer hasServer) { httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer); } public static HasServer getHasServerFromContext(ServletContext context) { return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY); } /** * Get http policy. * * @param conf the HAS config * @return HttpConfig.Policy the policy */ public HttpConfig.Policy getHttpPolicy(HasConfig conf) { String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY, WebConfigKey.HAS_HTTP_POLICY_DEFAULT); HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr); if (policy == null) { throw new HadoopIllegalArgumentException("Unrecognized value '" + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY); } conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name()); return policy; } /** * Return a HttpServer.Builder that the HAS can use to * initialize their HTTP / HTTPS server. * * @param conf the HAS config * @param httpAddr the InetSocketAddress of http * @param httpsAddr the InetSocketAddress of https * @param name the host name * @return HttpServer2.Builder the builder * @throws HasException HAS exception */ public HttpServer2.Builder httpServerTemplateForHAS( HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name) throws HasException { HttpConfig.Policy policy = getHttpPolicy(conf); HttpServer2.Builder builder = new HttpServer2.Builder().setName(name); if (policy.isHttpEnabled()) { if (httpAddr != null && httpAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } if (policy.isHttpsEnabled() && httpsAddr != null) { HasConfig sslConf = loadSslConfiguration(conf); loadSslConfToHttpServerBuilder(builder, sslConf); if (httpsAddr != null && httpsAddr.getPort() == 0) { builder.setFindPort(true); } URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr)); builder.addEndpoint(uri); LOG.info("Starting Web-server for " + name + " at: " + uri); } return builder; } /** * Load HTTPS-related configuration. * * @param conf HAS config * @return HasConfig after loading ssl configuration * @throws HasException HAS exception when loading HTTPS related configuration */ public HasConfig loadSslConfiguration(HasConfig conf) throws HasException { HasConfig sslConf = new HasConfig(); String sslConfigString = conf.getString( WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT); LOG.info("Get the ssl config file: " + sslConfigString); File sslConfig = new File(sslConfigString); if (!sslConfig.exists()) { throw new HasException("The ssl server config file " + sslConfigString + " does not exist."); } try { sslConf.addIniConfig(sslConfig); } catch (IOException e) { throw new HasException("Errors occurred when adding config. " + e.getMessage()); } final String[] reqSslProps = { WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY }; // Check if the required properties are included for (String sslProp : reqSslProps) { if (sslConf.getString(sslProp) == null) { LOG.warn("SSL config " + sslProp + " is missing. If " + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY + " is specified, make sure it is a relative path"); } } boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT); sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth); return sslConf; } public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder, HasConfig sslConf) { return builder .needsClientAuth( sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT)) .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY)) .keyStore(sslConf.getString("ssl.server.keystore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.keystore.type", "jks")) .trustStore(sslConf.getString("ssl.server.truststore.location"), getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY), sslConf.getString("ssl.server.truststore.type", "jks")) .excludeCiphers( sslConf.getString("ssl.server.exclude.cipher.list")); } /** * Leverages the Configuration.getPassword method to attempt to get * passwords from the CredentialProvider API before falling back to * clear text in config - if falling back is allowed. * * @param conf Configuration instance * @param alias name of the credential to retreive * @return String credential value or null */ public String getPassword(HasConfig conf, String alias) { return conf.getString(alias); } public void stop() throws Exception { if (httpServer != null) { httpServer.stop(); } } public InetSocketAddress getHttpAddress() { return httpAddress; } public InetSocketAddress getHttpsAddress() { return httpsAddress; } } |
blob | Long Method, Blob, Data Class | t | f | t | Long Method, Data Class | 0 | 11427 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java/#L43-L374 | 1 | 1600 | 11427 | major | |
| 2287 | YES I found bad smells The bad smells are: 1. Long class 2. Data class 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | Long class2 Data class3 Primitive obsession | t | f | t | 0 | 13890 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 2 | 2287 | 13890 | major | ||
| 2149 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static RuleSet parse(final Reader configReader, EventLoggerProvider eventLogger) { RuleSetCreator ruleSetCreator = new RuleSetCreator(); int line = 0; try(Reader fileReader = configReader) { LOGGER.debug("About to load ACL file"); StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(fileReader)); tokenizer.resetSyntax(); // setup the tokenizer tokenizer.commentChar(COMMENT); // single line comments tokenizer.eolIsSignificant(true); // return EOL as a token tokenizer.ordinaryChar('='); // equals is a token tokenizer.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) tokenizer.quoteChar('"'); // double quote tokenizer.quoteChar('\''); // single quote tokenizer.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly tokenizer.wordChars('a', 'z'); // unquoted token characters [a-z] tokenizer.wordChars('A', 'Z'); // [A-Z] tokenizer.wordChars('0', '9'); // [0-9] tokenizer.wordChars('_', '_'); // underscore tokenizer.wordChars('-', '-'); // dash tokenizer.wordChars('.', '.'); // dot tokenizer.wordChars('*', '*'); // star tokenizer.wordChars('@', '@'); // at tokenizer.wordChars(':', ':'); // colon // parse the acl file lines Stack stack = new Stack<>(); int current; do { current = tokenizer.nextToken(); line = tokenizer.lineno()-1; switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, line)); } // check for and parse optional initial number for ACL lines Integer number = null; if (first != null && first.matches("\\d+")) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (ACL.equalsIgnoreCase(first)) { parseAcl(number, stack, ruleSetCreator, line); } else if (number == null) { if("GROUP".equalsIgnoreCase(first)) { throw new IllegalConfigurationException(String.format("GROUP keyword not supported at " + "line %d. Groups should defined " + "via a Group Provider, not in " + "the ACL file.", line)); } else if (CONFIG.equalsIgnoreCase(first)) { parseConfig(stack, ruleSetCreator, line); } else { throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, line)); } } else { throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, line)); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(tokenizer.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(tokenizer.sval); // token break; default: if (tokenizer.ttype == CONTINUATION) { int next = tokenizer.nextToken(); line = tokenizer.lineno()-1; if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line because we ate the EOL) throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, line + 1)); } else if (tokenizer.ttype == '\'' || tokenizer.ttype == '"') { stack.push(tokenizer.sval); // quoted token } else { stack.push(Character.toString((char) tokenizer.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, line)); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, line), iae); } catch (IOException ioe) { throw new IllegalConfigurationException(CANNOT_LOAD_MSG, ioe); } return ruleSetCreator.createRuleSet(eventLogger); } |
long method | Feature envy, 2Long method | t | f | t | .Feature envy | 0 | 13283 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclFileParser.java/#L113-L249 | 2 | 2149 | 13283 | major | |
| 4213 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 11089 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 1 | 4213 | 11089 | minor | |
| 1309 | YES I found bad smells the bad smells are: 1. Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell. 2. Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes, indicating a potential feature envy smell2 Long method: The method "toBulkOperation" is quite long and contains multiple branches and nested logic, indicating a potential long method smell | t | f | t | . Feature envy: The method "toBulkOperation" contains a lot of code that is dependent on other classes | 0 | 10679 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 2 | 1309 | 10679 | critical | |
| 1601 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class OfflineIteratorEnvironment implements IteratorEnvironment { private final Authorizations authorizations; private AccumuloConfiguration conf; private boolean useSample; private SamplerConfiguration sampleConf; public OfflineIteratorEnvironment(Authorizations auths, AccumuloConfiguration acuTableConf, boolean useSample, SamplerConfiguration samplerConf) { this.authorizations = auths; this.conf = acuTableConf; this.useSample = useSample; this.sampleConf = samplerConf; } @Deprecated @Override public AccumuloConfiguration getConfig() { return conf; } @Override public IteratorScope getIteratorScope() { return IteratorScope.scan; } @Override public boolean isFullMajorCompaction() { return false; } @Override public boolean isUserCompaction() { return false; } private ArrayList> topLevelIterators = new ArrayList<>(); @Deprecated @Override public void registerSideChannel(SortedKeyValueIterator iter) { topLevelIterators.add(iter); } @Override public Authorizations getAuthorizations() { return authorizations; } SortedKeyValueIterator getTopLevelIterator(SortedKeyValueIterator iter) { if (topLevelIterators.isEmpty()) return iter; ArrayList> allIters = new ArrayList<>(topLevelIterators); allIters.add(iter); return new MultiIterator(allIters, false); } @Override public boolean isSamplingEnabled() { return useSample; } @Override public SamplerConfiguration getSamplerConfiguration() { return sampleConf; } @Override public IteratorEnvironment cloneWithSamplingEnabled() { if (sampleConf == null) throw new SampleNotPresentException(); return new OfflineIteratorEnvironment(authorizations, conf, true, sampleConf); } } |
data class | Data Class | t | f | t | 0 | 11429 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/clientImpl/OfflineIterator.java/#L70-L143 | 1 | 1601 | 11429 | minor | ||
| 632 | {"message": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | long method | t | t | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 1 | 632 | 6293 | major | ||
| 751 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JavaTimeSupplementary_es_AR extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final String[] sharedAmPmMarkers = { "a.m.", "p.m.", }; final String[] sharedDatePatterns = { "GGGG y MMMM d, EEEE", "GGGG y MMMM d", "GGGG y MMM d", "dd/MM/yy G", }; final String[] sharedDayNarrows = { "d", "l", "m", "m", "j", "v", "s", }; final String[] sharedTimePatterns = { "HH:mm:ss zzzz", "HH:mm:ss z", "HH:mm:ss", "HH:mm", }; final String[] sharedJavaTimeDatePatterns = { "G y MMMM d, EEEE", "G y MMMM d", "G y MMM d", "dd/MM/yy GGGGG", }; return new Object[][] { { "field.dayperiod", "a.m./p.m." }, { "islamic.AmPmMarkers", sharedAmPmMarkers }, { "islamic.DatePatterns", sharedDatePatterns }, { "islamic.DayNarrows", sharedDayNarrows }, { "islamic.TimePatterns", sharedTimePatterns }, { "islamic.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "islamic.narrow.AmPmMarkers", sharedAmPmMarkers }, { "java.time.buddhist.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.islamic.DatePatterns", sharedJavaTimeDatePatterns }, { "java.time.roc.DatePatterns", sharedJavaTimeDatePatterns }, { "roc.AmPmMarkers", sharedAmPmMarkers }, { "roc.DatePatterns", sharedDatePatterns }, { "roc.DayNarrows", sharedDayNarrows }, { "roc.MonthAbbreviations", new String[] { "ene.", "feb.", "mar.", "abr.", "may.", "jun.", "jul.", "ago.", "sep.", "oct.", "nov.", "dic.", "", } }, { "roc.MonthNarrows", new String[] { "e", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d", "", } }, { "roc.TimePatterns", sharedTimePatterns }, { "roc.abbreviated.AmPmMarkers", sharedAmPmMarkers }, { "roc.narrow.AmPmMarkers", sharedAmPmMarkers }, }; } } |
data class | long method, blob, data class | t | t | t | long method, blob | 0 | 7030 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.localedata/share/classes/sun/text/resources/ext/JavaTimeSupplementary_es_AR.java/#L72-L180 | 1 | 751 | 7030 | minor | |
| 36 |
{ "response": "YES I found bad smells", "bad smells are": [ "Long method" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unused") private String format(String s, Object[] arguments) { if (arguments == null) { return s; } // A very simple implementation of format int i = 0; while (i < arguments.length) { String delimiter = "{" + i + "}"; while (s.contains(delimiter)) { s = s.replace(delimiter, String.valueOf(arguments[i])); } i++; } return s; } |
long method | long method | t | t | t | 0 | 754 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/GwtKuraException.java/#L148-L165 | 2 | 36 | 754 | minor | ||
| 501 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Feature Envy", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @JacksonXmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class User implements Serializable { private static final long serialVersionUID = 4247427179764560935L; private Integer id; private String username; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String email; private String url; private String description; private String link; private String locale; private String nickname; private String slug; @JsonProperty("registered_date") private String registeredDate; private List roles; private Map capabilities; @JsonProperty("extra_capabilities") private Map extraCapabilities; @JsonProperty("avatar_urls") private Map avatarUrls; @JsonProperty("meta") private List> meta; public User() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getRegisteredDate() { return registeredDate; } public void setRegisteredDate(String registeredDate) { this.registeredDate = registeredDate; } public List getRoles() { return roles; } public void setRoles(List roles) { this.roles = roles; } public Map getCapabilities() { return capabilities; } public void setCapabilities(Map capabilities) { this.capabilities = capabilities; } public Map getExtraCapabilities() { return extraCapabilities; } public void setExtraCapabilities(Map extraCapabilities) { this.extraCapabilities = extraCapabilities; } public Map getAvatarUrls() { return avatarUrls; } public void setAvatarUrls(Map avatarUrls) { this.avatarUrls = avatarUrls; } public List> getMeta() { return meta; } public void setMeta(List> meta) { this.meta = meta; } @Override public String toString() { return toStringHelper(this).addValue(this.id).addValue(this.username).addValue(this.email).addValue(this.name).toString(); } } |
data class | feature envy, data class | t | t | f | feature envy | data class | 0 | 5079 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/User.java/#L29-L213 | 1 | 501 | 5079 | major |
| 101 | {"message": "YES I found bad smells the bad smells are:", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class CountPageable implements Pageable { private Pageable delegate; public CountPageable(Pageable delegate) { this.delegate = delegate; } public int getPageNumber() { return delegate.getPageNumber(); } public int getPageSize() { return delegate.getPageSize(); } public long getOffset() { return delegate.getOffset(); } public Sort getSort() { // Sorting is not allowed on aggregate count queries. return Sort.unsorted(); } public Pageable next() { return delegate.next(); } public Pageable previousOrFirst() { return delegate.previousOrFirst(); } public Pageable first() { return delegate.first(); } public boolean hasPrevious() { return delegate.hasPrevious(); } } |
data class | data class | t | t | t | 0 | 1307 | https://github.com/spring-projects/spring-data-couchbase/blob/2f4500e9c76541bbbd6a612f7b9283d2455a2dc6/src/main/java/org/springframework/data/couchbase/repository/query/N1qlCountQueryCreator.java/#L83-L124 | 1 | 101 | 1307 | critical | ||
| 1226 | YES I found bad smells The bad smells are: 1. Duplicate code (calling findNuageVspCmsIdForDeviceOrHost() twice) 2. Long method 3. Feature envy (method is using data from NuageVspDeviceVO instead of its own data) 4. Use of null instead of proper error handling 5. Possible use of magic numbers (SyncType.REGISTER is compared multiple times) 6. Complex conditional logic (multiple if/else statements) 7. Unnecessary parameter passing (nuageVspDevice.getHostId() is passed to multiple methods) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
feature envy | Duplicate code (calling findNuageVspCmsIdForDeviceOrHost() twice)2 Long method3 Feature envy (method is using data from NuageVspDeviceVO instead of its own data)4 Use of null instead of proper error handling5 Possible use of magic numbers (SyncTypeREGISTER is compared multiple times)6 Complex conditional logic (multiple if/else statements)7 Unnecessary parameter passing (nuageVspDevicegetHostId() is passed to multiple methods) | t | f | t | 0 | 10352 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 1226 | 10352 | minor | ||
| 2348 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | data class | t | t | t | 0 | 14198 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 2348 | 14198 | major | ||
| 3634 | YES I found bad smells the bad smells are: 1. Long method 2. Magic number usage (values such as ILLEGAL_PROCESS_ID and ILLEGAL_INVOKE_ID are not easily understandable without context) 3. Feature envy (the method is accessing multiple fields from the immediatelyThrowsEvent object, indicating that the logic might be better placed inside the object itself) 4. Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed) 5. Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ImmediatelyThrowsEvent makeImmediatelyThrowsEvent(final int processId, final int invokeId, final Throwable throwable) { if (null == immediatelyThrowsEvent) { immediatelyThrowsEvent = new ImmediatelyThrowsEvent(ILLEGAL_PROCESS_ID, ILLEGAL_INVOKE_ID, null); } unsafe.putInt(immediatelyThrowsEvent, processIdFieldInInvokeEventOffset, processId); unsafe.putInt(immediatelyThrowsEvent, invokeIdFieldInInvokeEventOffset, invokeId); unsafe.putObject(immediatelyThrowsEvent, throwableFieldInThrowsEventOffset, throwable); return immediatelyThrowsEvent; } |
feature envy | Long method2 Magic number usage (values such as ILLEGAL_PROCESS_ID and ILLEGAL_INVOKE_ID are not easily understandable without context)3 Feature envy (the method is accessing multiple fields from the immediatelyThrowsEvent object, indicating that the logic might be better placed inside the object itself)4 Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed)5 Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | t | f | t | indicating that the logic might be better placed inside the object itself)4. Possible duplicate code (the immediatelyThrowsEvent object is always initialized with the same values, so the if statement could potentially be removed)5. Insufficient error handling (the method doesn't perform any checks to ensure that the provided parameters are valid and could throw an exception) | 0 | 8213 | https://github.com/alibaba/jvm-sandbox/blob/5ff3554ce2fcbe5eb9dd0ecc01c31a1d53c3c12e/sandbox-core/src/main/java/com/alibaba/jvm/sandbox/core/enhance/weaver/SingleEventFactory.java/#L130-L140 | 2 | 3634 | 8213 | minor | |
| 1763 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long Method | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 1763 | 11896 | minor | ||
| 2226 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Header { public String key; public String val; public Header(String key, String val) { this.key = key; this.val = val; } public String getEncodedKey() { return encode(key); } public String getEncodedValue() { return encode(val); } } |
data class | blob, data class | t | t | t | blob | 0 | 13576 | https://github.com/apache/activemq-artemis/blob/5bd5c610195d6f4a3dd1ac28170727003f8a5a54/artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/StompFrame.java/#L158-L175 | 1 | 2226 | 13576 | major | |
| 80 | {"message": "YES I found bad smells", "bad smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: abstract static class RequestParamsBuilder { T body; public RequestParamsBuilder(T body) { this.body = body; } abstract RequestParams buildRequestParams(); void setBody(T body) { this.body = body; } } |
data class | blob, data class | t | t | t | blob | 0 | 1185 | https://github.com/oracle/weblogic-kubernetes-operator/blob/1fb059d7e32b9b3514617d54e4dda41ab68e71ea/operator/src/main/java/oracle/kubernetes/operator/helpers/CallBuilder.java/#L179-L191 | 1 | 80 | 1185 | critical | |
| 2914 | {"message": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | 1. data class | t | t | t | 0 | 2250 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 1 | 2914 | 2250 | major | ||
| 2336 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | data class, long method | t | t | t | long method | 0 | 14164 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 1 | 2336 | 14164 | major | |
| 3589 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException { Assert.state(target != null, "Target must not be null"); Class type = (target instanceof Class ? (Class) target : target.getClass()); if (type.isArray() && name.equals("length")) { if (target instanceof Class) { throw new AccessException("Cannot access length on array class itself"); } return new TypedValue(Array.getLength(target)); } PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class); InvokerPair invoker = this.readerCache.get(cacheKey); this.lastReadInvokerPair = invoker; if (invoker == null || invoker.member instanceof Method) { Method method = (Method) (invoker != null ? invoker.member : null); if (method == null) { method = findGetterForProperty(name, type, target); if (method != null) { // Treat it like a property... // The readerCache will only contain gettable properties (let's not worry about setters for now). Property property = new Property(type, method, null); TypeDescriptor typeDescriptor = new TypeDescriptor(property); invoker = new InvokerPair(method, typeDescriptor); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (method != null) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter method", ex); } } } if (invoker == null || invoker.member instanceof Field) { Field field = (Field) (invoker == null ? null : invoker.member); if (field == null) { field = findField(name, type, target); if (field != null) { invoker = new InvokerPair(field, new TypeDescriptor(field)); this.lastReadInvokerPair = invoker; this.readerCache.put(cacheKey, invoker); } } if (field != null) { try { ReflectionUtils.makeAccessible(field); Object value = field.get(target); return new TypedValue(value, invoker.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } } throw new AccessException("Neither getter method nor field found for property '" + name + "'"); } |
long method | long method, data class | t | t | t | data class | 0 | 7923 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java/#L157-L222 | 1 | 3589 | 7923 | major | |
| 2115 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static DimFilter negate(final DimFilter filter) { if (Filtration.matchEverything().equals(filter)) { return Filtration.matchNothing(); } else if (Filtration.matchNothing().equals(filter)) { return Filtration.matchEverything(); } else if (filter instanceof NotDimFilter) { return ((NotDimFilter) filter).getField(); } else if (filter instanceof BoundDimFilter) { final BoundDimFilter negated = Bounds.not((BoundDimFilter) filter); return negated != null ? negated : new NotDimFilter(filter); } else { return new NotDimFilter(filter); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 13193 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/sql/src/main/java/org/apache/druid/sql/calcite/filtration/CombineAndSimplifyBounds.java/#L221-L235 | 2 | 2115 | 13193 | minor | ||
| 1522 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | Blob, Data Class, Long Method | t | f | t | Blob, Long Method | 0 | 11174 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 1 | 1522 | 11174 | minor | |
| 1051 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Long parameter list", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
feature envy | long method, long parameter list, feature envy | t | t | t | long method, long parameter list | 0 | 9477 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 2 | 1051 | 9477 | major | |
| 1229 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ObjectLruCache extends AbstractLruCache { /** The array of values */ Object[] values = new Object[INITIAL_SIZE]; /** * Create a new ObjectLruCache. * @param maxSize the maximum size the cache can grow to */ public ObjectLruCache(int maxSize) { super(maxSize); } /** * Overridden method to return values array. */ Object getValuesArray() { return values; } /** * Overridden method to allocate new values array. */ void allocNewValuesArray(int newSize) { super.allocNewValuesArray(newSize); values = new Object[newSize]; } /** * Overridden method to repopulate with key plus value at given offset. */ void put(long key, Object oldvalues, int offset) { Object[] v = (Object[])oldvalues; put(key, v[offset]); } /** * Returns the value mapped by the given key. Also promotes this key to the most * recently used. * @return the value or null if it cannot be found */ public Object get(long key) { int index = getIndexAndPromote(key) ; if (index != -1) { return values[index]; } return null; } /** * Add the key/value pair to the map. */ public void put(long key, Object value) { int index = putIndexAndPromote(key) ; values[index] = value; checkRehash(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10360 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/openj9.dtfj/share/classes/com/ibm/dtfj/corereaders/zos/util/ObjectLruCache.java/#L32-L89 | 1 | 1229 | 10360 | major | |
| 929 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _ParameterFieldReference extends _ParameterValueOrFieldReference implements ElementSerializable, ElementDeserializable { // No attributes // Elements protected String parameterName; protected String fieldAlias; public _ParameterFieldReference() { super(); } public _ParameterFieldReference( final String parameterName, final String fieldAlias) { // TODO : Call super() instead of setting all fields directly? setParameterName(parameterName); setFieldAlias(fieldAlias); } public String getParameterName() { return this.parameterName; } public void setParameterName(String value) { this.parameterName = value; } public String getFieldAlias() { return this.fieldAlias; } public void setFieldAlias(String value) { this.fieldAlias = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Declare our type writer.writeAttribute( "xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "ParameterFieldReference"); // Elements XMLStreamWriterHelper.writeElement( writer, "ParameterName", this.parameterName); XMLStreamWriterHelper.writeElement( writer, "FieldAlias", this.fieldAlias); writer.writeEndElement(); } public void readFromElement(final XMLStreamReader reader) throws XMLStreamException { String localName; // This object uses no attributes // Elements int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); if (localName.equalsIgnoreCase("ParameterName")) { this.parameterName = reader.getElementText(); } else if (localName.equalsIgnoreCase("FieldAlias")) { this.fieldAlias = reader.getElementText(); } else { // Read the unknown child element until its end XMLStreamReaderHelper.readUntilElementEnd(reader); } } } while (event != XMLStreamConstants.END_ELEMENT); } } |
data class | data class | t | t | t | 0 | 8340 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/sql/reporting/reportingservices/_ParameterFieldReference.java/#L31-L137 | 1 | 929 | 8340 | minor | ||
| 932 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Long parameter list 4. Duplicate code 5. Comments that explain bad code 6. Nested conditionals 7. Inappropriate level of abstraction 8. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | Long method2 Feature envy3 Long parameter list4 Duplicate code5 Comments that explain bad code 6 Nested conditionals7 Inappropriate level of abstraction8 Inconsistent naming conventions | t | f | t | 0 | 8357 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 2 | 932 | 8357 | major | ||
| 695 | {"response": "YES I found bad smells\nthe bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | 1. long method | t | t | t | 0 | 6659 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 1 | 695 | 6659 | major | ||
| 1652 | {"response": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class CheProductInfoDataProvider extends ProductInfoDataProviderImpl { private final LocalizationConstant locale; private final Resources resources; @Inject public CheProductInfoDataProvider(LocalizationConstant locale, Resources resources) { this.locale = locale; this.resources = resources; } @Override public String getName() { return locale.getProductName(); } @Override public String getSupportLink() { return locale.getSupportLink(); } @Override public String getDocumentTitle() { return locale.cheTabTitle(); } @Override public String getDocumentTitle(String workspaceName) { return locale.cheTabTitle(workspaceName); } @Override public SVGResource getLogo() { return resources.logo(); } @Override public SVGResource getWaterMarkLogo() { return resources.waterMarkLogo(); } @Override public String getSupportTitle() { return locale.supportTitle(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11582 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/plugins/plugin-product-info/src/main/java/org/eclipse/che/plugin/product/info/client/CheProductInfoDataProvider.java/#L26-L72 | 1 | 1652 | 11582 | minor | |
| 2050 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | long method | t | t | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 1 | 2050 | 12885 | minor | ||
| 1665 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long method2 Feature envy | t | f | t | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1665 | 11622 | minor | ||
| 3454 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. */ @Parameter( property = "project.build.directory", required = true ) protected File targetDirectory; /** * The output directory for the final HTML report. Note that this parameter is only evaluated if the goal is run * directly from the command line or during the default lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is used instead. */ @Parameter( property = "project.reporting.outputDirectory", required = true ) protected File outputDirectory; /** * Site rendering component for generating the HTML report. */ @Component private Renderer siteRenderer; /** * The project to analyse. */ @Parameter( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available * renderers. XML is required if the pmd:check goal is being used. */ @Parameter( property = "format", defaultValue = "xml" ) protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ @Parameter( property = "linkXRef", defaultValue = "true" ) private boolean linkXRef; /** * Location of the Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) private File xrefLocation; /** * Location of the Test Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these * exclusion patterns only operate on the path of a source file relative to its source root directory. In other * words, files are excluded based on their package and/or class name. If you want to exclude entire source root * directories, use the parameter excludeRoots instead. * * @since 2.2 */ @Parameter private List excludes; /** * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to * **\/*.java. * * @since 2.2 */ @Parameter private List includes; /** * Specifies the location of the source directories to be used for PMD. * Defaults to project.compileSourceRoots. * @since 3.7 */ @Parameter( defaultValue = "${project.compileSourceRoots}" ) private List compileSourceRoots; /** * The directories containing the test-sources to be used for PMD. * Defaults to project.testCompileSourceRoots * @since 3.7 */ @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 */ @Parameter private File[] excludeRoots; /** * Run PMD on the tests. * * @since 2.2 */ @Parameter( defaultValue = "false" ) protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @since 2.2 */ @Parameter( property = "aggregate", defaultValue = "false" ) protected boolean aggregate; /** * The file encoding to use when reading the Java sources. * * @since 2.3 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String sourceEncoding; /** * The file encoding when writing non-HTML reports. * * @since 2.5 */ @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) private String outputEncoding; /** * The projects in the reactor for aggregation report. */ @Parameter( property = "reactorProjects", readonly = true ) protected List reactorProjects; /** * Whether to include the xml files generated by PMD/CPD in the site. * * @since 3.0 */ @Parameter( defaultValue = "false" ) protected boolean includeXmlInSite; /** * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to * true. * * @since 3.1 */ @Parameter( defaultValue = "true" ) protected boolean skipEmptyReport; /** * File that lists classes and rules to be excluded from failures. * For PMD, this is a properties file. For CPD, this * is a text file that contains comma-separated lists of classes * that are allowed to duplicate. * * @since 3.7 */ @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) protected String excludeFromFailureFile; /** The files that are being analyzed. */ protected Map filesToProcess; /** * {@inheritDoc} */ @Override protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ @Override protected Renderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way @SuppressWarnings( "unchecked" ) List reportPlugins = project.getReportPlugins(); for ( ReportPlugin plugin : reportPlugins ) { String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ protected Map getFilesToProcess() throws IOException { if ( aggregate && !project.isExecutionRoot() ) { return Collections.emptyMap(); } if ( excludeRoots == null ) { excludeRoots = new File[0]; } Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); for ( File file : excludeRoots ) { if ( file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList<>(); if ( null == compileSourceRoots ) { compileSourceRoots = project.getCompileSourceRoots(); } if ( compileSourceRoots != null ) { for ( String root : compileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } } } if ( null == testSourceRoots ) { testSourceRoots = project.getTestCompileSourceRoots(); } if ( includeTests ) { if ( testSourceRoots != null ) { for ( String root : testSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } } } if ( aggregate ) { for ( MavenProject localProject : reactorProjects ) { @SuppressWarnings( "unchecked" ) List localCompileSourceRoots = localProject.getCompileSourceRoots(); for ( String root : localCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } } if ( includeTests ) { @SuppressWarnings( "unchecked" ) List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); for ( String root : localTestCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } } String excluding = getExcludes(); getLog().debug( "Exclusions: " + excluding ); String including = getIncludes(); getLog().debug( "Inclusions: " + including ); Map files = new TreeMap<>(); for ( PmdFileInfo finfo : directories ) { getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); for ( File newfile : newfiles ) { files.put( newfile.getCanonicalFile(), finfo ); } } } return files; } private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) { boolean returnVal = false; for ( File excludeDir : excludeRootFiles ) { try { if ( sourceDirectoryToCheck.getCanonicalPath().startsWith( excludeDir.getCanonicalPath() ) ) { getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() + " has been excluded as it matches excludeRoot " + excludeDir.getAbsolutePath() ); returnVal = true; break; } } catch ( IOException e ) { getLog().warn( "Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e ); } } return returnVal; } /** * Gets the comma separated list of effective include patterns. * * @return The comma separated list of effective include patterns, never null. */ private String getIncludes() { Collection patterns = new LinkedHashSet<>(); if ( includes != null ) { patterns.addAll( includes ); } if ( patterns.isEmpty() ) { patterns.add( "**/*.java" ); } return StringUtils.join( patterns.iterator(), "," ); } /** * Gets the comma separated list of effective exclude patterns. * * @return The comma separated list of effective exclude patterns, never null. */ private String getExcludes() { Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); if ( excludes != null ) { patterns.addAll( excludes ); } return StringUtils.join( patterns.iterator(), "," ); } protected boolean isHtml() { return "html".equals( format ); } protected boolean isXml() { return "xml".equals( format ); } /** * {@inheritDoc} */ @Override public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } if ( "pom".equals( project.getPackaging() ) && !aggregate ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( isXml() ) { return true; } try { filesToProcess = getFilesToProcess(); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * {@inheritDoc} */ @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } protected String getSourceEncoding() { return sourceEncoding; } /** * Gets the effective reporting output files encoding. * * @return The effective reporting output file encoding, never null. * @since 2.5 */ protected String getOutputEncoding() { return ( outputEncoding != null ) ? outputEncoding : ReaderFactory.UTF_8; } static String getPmdVersion() { try { return (String) PMD.class.getField( "VERSION" ).get( null ); } catch ( IllegalAccessException e ) { throw new RuntimeException( "PMD VERSION field not accessible", e ); } catch ( NoSuchFieldException e ) { throw new RuntimeException( "PMD VERSION field not found", e ); } } } |
data class | data class, long method | t | t | t | long method | 0 | 6936 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-pmd-plugin/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java/#L52-L553 | 1 | 3454 | 6936 | minor | |
| 2153 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Mix of responsibilities (method is responsible for too many things) 4. Inconsistent formatting and naming conventions 5. Arbitrary integer value used without clear explanation or justification 6. Nested if statements 7. Use of null values 8. Use of raw data types instead of object-oriented approach 9. Potential for null pointer exception 10. Potential for index out of bounds exception 11. Magic numbers/strings used (e.g. 0, "0") 12. Violation of the Single Responsibility Principle (SRP) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | Long method2 Duplicate code3 Mix of responsibilities (method is responsible for too many things)4 Inconsistent formatting and naming conventions5 Arbitrary integer value used without clear explanation or justification6 Nested if statements7 Use of null values8 Use of raw data types instead of object-oriented approach9 Potential for null pointer exception | t | f | t | 0 | 13295 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 2153 | 13295 | minor | ||
| 2548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | long method, data class | t | t | t | data class | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 1 | 2548 | 14793 | minor | |
| 5781 | {"message": "YES, I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15317 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5781 | 15317 | minor | ||
| 1388 | Yes I found bad smells the bad smells are: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, 10. Hard-coded values/strings, 11. Use of deprecated methods, 12. Lack of abstraction/separation of concerns, 13. Potential NullPointerExceptions, 14. Unused variables, 15. Lack of error handling/reporting, 16. Inadequate naming of variables/methods. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Magic numbers, 5 Nested conditionals, 6 Large number of parameters, 7 Lack of comments/documentation, 8 High complexity/low readability, 9 Inconsistent formatting, | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Magic numbers, 5. Nested conditionals, 6. Large number of parameters, 7. Lack of comments/documentation, 8. High complexity/low readability, 9. Inconsistent formatting, | 0 | 10839 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1388 | 10839 | critical | |
| 983 | { "message": "YES I found bad smells", "bad smells are": ["Blob", "Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
data class | blob, long method, data class | t | t | t | blob, long method | 0 | 8862 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 1 | 983 | 8862 | minor | |
| 2298 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | long method, data class | t | t | t | data class | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 1 | 2298 | 14025 | major | |
| 2565 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | data class | t | t | t | 0 | 14856 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 2565 | 14856 | major | ||
| 59 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | blob, data class | t | t | t | blob | 0 | 1004 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 59 | 1004 | critical | |
| 484 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method2 Feature envy | t | f | t | 0 | 4743 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 484 | 4743 | minor | ||
| 1612 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExtendedCompletionList { private boolean inComplete; private List items; public ExtendedCompletionList(boolean incomplete, List items) { this.inComplete = incomplete; this.items = items; } public ExtendedCompletionList() {} public List getItems() { return items; } public void setItems(List items) { this.items = items; } public boolean isInComplete() { return inComplete; } public void setInComplete(boolean inComplete) { this.inComplete = inComplete; } } |
data class | Data Class | t | f | t | 0 | 11467 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/model/ExtendedCompletionList.java/#L22-L48 | 1 | 1612 | 11467 | minor | ||
| 1589 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Capability implements IConvertible { private String virtualCores; private String memorySize; private String memory; public String getVirtualCores() { return virtualCores; } public void setVirtualCores(String virtualCores) { this.virtualCores = virtualCores; } public String getMemorySize() { return memorySize; } public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } } |
data class | Data Class | t | f | t | 0 | 11385 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/yarn/rm/Capability.java/#L26-L56 | 1 | 1589 | 11385 | minor | ||
| 564 | { "message": "YES I found bad smells", "detected_bad_smells": { "are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class DrillScanRelBase extends TableScan implements DrillRelNode { protected GroupScan groupScan; protected final DrillTable drillTable; public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, RelOptTable table, final List columns) { super(cluster, traits, table); this.drillTable = Utilities.getDrillTable(table); assert drillTable != null; try { this.groupScan = drillTable.getGroupScan().clone(columns); } catch (final IOException e) { throw new DrillRuntimeException("Failure creating scan.", e); } } public DrillScanRelBase(RelOptCluster cluster, RelTraitSet traits, GroupScan grpScan, RelOptTable table) { super(cluster, traits, table); DrillTable unwrap = table.unwrap(DrillTable.class); if (unwrap == null) { unwrap = table.unwrap(DrillTranslatableTable.class).getDrillTable(); } this.drillTable = unwrap; assert drillTable != null; this.groupScan = grpScan; } public DrillTable getDrillTable() { return drillTable; } public GroupScan getGroupScan() { return groupScan; } @Override public double estimateRowCount(RelMetadataQuery mq) { return mq.getRowCount(this); } @Override public RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) { double dRows = estimateRowCount(mq); double dCpu = dRows + 1; // ensure non-zero cost double dIo = 0; return planner.getCostFactory().makeCost(dRows, dCpu, dIo); } } |
data class | are: data class | t | t | t | 0 | 5711 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/planner/common/DrillScanRelBase.java/#L39-L89 | 1 | 564 | 5711 | minor | ||
| 2426 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | long method | t | t | t | 0 | 14445 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 1 | 2426 | 14445 | minor | ||
| 2605 | {"response": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Signal { public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED }; Type type; String value = ""; Exception exception = null; Signal(Type type, String value) { this.type = type; this.value = value; this.exception = null; } Signal(Type type, String value, Exception exception) { this.type = type; this.value = value; this.exception = exception; } /** * Get the signal value (message text) */ public String getValue() { return value; } } |
data class | data class | t | t | t | 0 | 15028 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hplsql/src/main/java/org/apache/hive/hplsql/Signal.java/#L24-L48 | 1 | 2605 | 15028 | critical | ||
| 3479 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void startElement(final String uri, final String localName, final String qname, final Attributes attributes) throws SAXException { // Verify and initialize the context stack at root element. if (contextStack.size() == 0) { if (!qname.equals(rootElement)) { throw new SAXConfigurationException( new ConfigurationException.IncorrectElement(rootElement, qname, this.source, locator.getLineNumber()), locator); } String all = attributes.getValue("includeAllClasses"); if ("true".equals(all)) allClasses = true; contextStack.push(qname); return; } else { if (qname.equals("classEntry")) { String path = attributes.getValue("path"); includedClasses.add(path); } else if (qname.equals("namespaceManifestEntry")) { String manifest = attributes.getValue("manifest"); String namespace = attributes.getValue("namespace"); fbArgs.add("-namespace"); fbArgs.add(namespace); String mf = contextPath + "/" + manifest; File f = new File(mf); if (!f.exists()) { mf = contextPath + "/src/" + manifest; } fbArgs.add(mf); fbArgs.add("-include-namespaces"); fbArgs.add(namespace); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 7119 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/compiler-common/src/main/java/org/apache/royale/compiler/internal/config/FlashBuilderConfigurator.java/#L468-L510 | 2 | 3479 | 7119 | minor | ||
| 598 | {"response": "YES I found bad smells. The bad smells are: 1. Long method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | 1. long method | t | t | t | 0 | 5982 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 598 | 5982 | major | ||
| 2670 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 15211 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2670 | 15211 | major | ||
| 1305 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addUTF8Region(StructurePointer clazz, String slotName, String additionalInfo, AbstractPointer utf8String) throws CorruptDataException { long offset = utf8String.getAddress() - clazz.getAddress(); /* We do not want to print UTF8 outside of the ROM class. */ long clazzSize = ((J9ROMClassPointer) clazz).romSize().longValue(); if ((offset > 0) && (offset < clazzSize)) { if (utf8String.notNull()) { long UTF8Length = getUTF8Length(J9UTF8Pointer.cast(utf8String)); if (utf8String.getAddress() < firstJ9_ROM_UTF8) { firstJ9_ROM_UTF8 = utf8String.getAddress(); } if ((utf8String.getAddress() + UTF8Length) > lastJ9_ROM_UTF8) { lastJ9_ROM_UTF8 = utf8String.getAddress() + UTF8Length; } classRegions.add(new J9ClassRegion(utf8String, SlotType.J9_ROM_UTF8, slotName, additionalInfo, UTF8Length, offset, true)); } } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10673 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/debugtools/DDR_VM/src/com/ibm/j9ddr/vm29/tools/ddrinteractive/LinearDumper.java/#L277-L297 | 2 | 1305 | 10673 | minor | |
| 2283 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MqttConnectionState { // ******* Connection properties ******// private Integer receiveMaximum = 65535; private Integer maximumQoS = 2; private Boolean retainAvailable = true; private Long outgoingMaximumPacketSize = null; private Long incomingMaximumPacketSize = null; private Integer outgoingTopicAliasMaximum = 0; private Integer incomingTopicAliasMax = 0; private Boolean wildcardSubscriptionsAvailable = true; private Boolean subscriptionIdentifiersAvailable = true; private Boolean sharedSubscriptionsAvailable = true; private boolean sendReasonMessages = false; private long keepAlive = 60; // ******* Counters ******// private AtomicInteger nextOutgoingTopicAlias = new AtomicInteger(1); /** * Clears the session and resets. This would be called when the connection has * been lost and cleanStart = True. */ public void clearConnectionState() { nextOutgoingTopicAlias.set(1); } public Integer getReceiveMaximum() { if (receiveMaximum == null) { return 65535; } return receiveMaximum; } public void setReceiveMaximum(Integer receiveMaximum) { this.receiveMaximum = receiveMaximum; } public Integer getMaximumQoS() { return maximumQoS; } public void setMaximumQoS(Integer maximumQoS) { this.maximumQoS = maximumQoS; } public Boolean isRetainAvailable() { return retainAvailable; } public void setRetainAvailable(Boolean retainAvailable) { this.retainAvailable = retainAvailable; } public Long getOutgoingMaximumPacketSize() { return outgoingMaximumPacketSize; } public void setOutgoingMaximumPacketSize(Long maximumPacketSize) { this.outgoingMaximumPacketSize = maximumPacketSize; } public Long getIncomingMaximumPacketSize() { return incomingMaximumPacketSize; } public void setIncomingMaximumPacketSize(Long incomingMaximumPacketSize) { this.incomingMaximumPacketSize = incomingMaximumPacketSize; } public Integer getOutgoingTopicAliasMaximum() { return outgoingTopicAliasMaximum; } public void setOutgoingTopicAliasMaximum(Integer topicAliasMaximum) { this.outgoingTopicAliasMaximum = topicAliasMaximum; } public Boolean isWildcardSubscriptionsAvailable() { return wildcardSubscriptionsAvailable; } public void setWildcardSubscriptionsAvailable(Boolean wildcardSubscriptionsAvailable) { this.wildcardSubscriptionsAvailable = wildcardSubscriptionsAvailable; } public Boolean isSubscriptionIdentifiersAvailable() { return subscriptionIdentifiersAvailable; } public void setSubscriptionIdentifiersAvailable(Boolean subscriptionIdentifiersAvailable) { this.subscriptionIdentifiersAvailable = subscriptionIdentifiersAvailable; } public Boolean isSharedSubscriptionsAvailable() { return sharedSubscriptionsAvailable; } public void setSharedSubscriptionsAvailable(Boolean sharedSubscriptionsAvailable) { this.sharedSubscriptionsAvailable = sharedSubscriptionsAvailable; } public Integer getNextOutgoingTopicAlias() { return nextOutgoingTopicAlias.getAndIncrement(); } public Integer getIncomingTopicAliasMax() { return incomingTopicAliasMax; } public void setIncomingTopicAliasMax(Integer incomingTopicAliasMax) { this.incomingTopicAliasMax = incomingTopicAliasMax; } public boolean isSendReasonMessages() { return sendReasonMessages; } public void setSendReasonMessages(boolean enableReasonMessages) { this.sendReasonMessages = enableReasonMessages; } public long getKeepAlive() { return keepAlive; } public void setKeepAliveSeconds(long keepAlive) { this.keepAlive = keepAlive * 1000; } } |
data class | long method, data class | t | t | t | long method | 0 | 13842 | https://github.com/eclipse/paho.mqtt.java/blob/5af7b53499e7dbe45b7227b3d41fc870089c0033/org.eclipse.paho.mqttv5.client/src/main/java/org/eclipse/paho/mqttv5/client/internal/MqttConnectionState.java/#L26-L168 | 1 | 2283 | 13842 | major | |
| 784 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 7494 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 784 | 7494 | minor | |
| 908 | { "answer": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | blob, long method | t | t | t | blob | 0 | 8202 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 1 | 908 | 8202 | minor | |
| 592 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy | t | f | t | 0 | 5902 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 592 | 5902 | minor | ||
| 1875 | { "message": "YES, I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 1875 | 12262 | minor | |
| 1829 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12118 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 2 | 1829 | 12118 | major | ||
| 2606 | YES I found bad smells the bad smells are: 1.Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
feature envy | Long method, 2 Feature envy | t | f | t | .Long method | 0 | 15029 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 2606 | 15029 | major | |
| 2380 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy, 3. Code duplication, 4. Complex conditional logic, 5. Inconsistent indentation, 6. Lack of comments/documentation, 7. Use of deprecated code, 8. Lack of exception handling, 9. Inefficient error handling using try-catch, 10. Use of block comments instead of line comments, 11. Nested synchronized blocks, 12. Lack of proper resource management using try-finally blocks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
feature envy | Long method, 2 Feature envy, 3 Code duplication, 4 Complex conditional logic, 5 Inconsistent indentation, 6 Lack of comments/documentation, 7 Use of deprecated code, 8 Lack of exception handling, 9 Inefficient error handling using try-catch, | t | f | t | . Long method, 3. Code duplication, 4. Complex conditional logic, 5. Inconsistent indentation, 6. Lack of comments/documentation, 7. Use of deprecated code, 8. Lack of exception handling, 9. Inefficient error handling using try-catch, | 0 | 14337 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2380 | 14337 | minor | |
| 2512 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Blob", "3. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class MqttMessageDeliveryEvent extends MqttIntegrationEvent { private final int messageId; private final String clientId; private final int clientInstance; public MqttMessageDeliveryEvent(Object source, int messageId, String clientId, int clientInstance) { super(source); this.messageId = messageId; this.clientId = clientId; this.clientInstance = clientInstance; } public int getMessageId() { return this.messageId; } public String getClientId() { return this.clientId; } public int getClientInstance() { return this.clientInstance; } } |
data class | 1. long method, 2. blob, 3. data class | t | t | t | 1. long method, 2. blob | 0 | 14689 | https://github.com/spring-projects/spring-integration/blob/872302de6e98c1fd34e3192d8e4de244008ca857/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/event/MqttMessageDeliveryEvent.java/#L28-L56 | 1 | 2512 | 14689 | major | |
| 209 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ProjectList extends DataType implements Cloneable { protected ArrayList list = new ArrayList(); /** * add a project * @param pro */ public void addProjectInfo(ProjectInfo pro) { list.add(pro); } /** * get project by index * @param index * @return */ public ProjectInfo getProject(int index) { assert(index>=0 && index<list.size()); return (ProjectInfo)list.get(index); } /** * get count * @return */ public int getCount() { return list.size(); } } |
data class | data class | t | t | t | 0 | 2311 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/build/org.eclipse.birt.build/src/org/eclipse/birt/build/ProjectList.java/#L24-L61 | 1 | 209 | 2311 | minor | ||
| 997 | {"message":"YES I found bad smells","bad_smells":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void getSuggestions(final String query) { if (query == null || query.isEmpty()) { return; } // Initialize the locatorSugestion parameters locatorParams(SUGGEST_PLACE); // Attach a listener to the locator task since // the LocatorTask may or may not be loaded the // the very first time a user types text into the search box. // If the Locator is already loaded, the following listener // is invoked immediately. mLocator.addDoneLoadingListener(new Runnable() { @Override public void run() { // Does this locator support suggestions? if (mLocator.getLoadStatus().name() != LoadStatus.LOADED.name()){ //Log.i(TAG,"##### " + mLocator.getLoadStatus().name()); } else if (!mLocator.getLocatorInfo().isSupportsSuggestions()){ return; } //og.i(TAG,"****** " + mLocator.getLoadStatus().name()); final ListenableFuture> suggestionsFuture = mLocator.suggestAsync(query, suggestParams); // Attach a done listener that executes upon completion of the async call suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the suggestions returned from the locator task. // Store retrieved suggestions for future use (e.g. if the user // selects a retrieved suggestion, it can easily be // geocoded). mSuggestionsList = suggestionsFuture.get(); showSuggestedPlaceNames(mSuggestionsList); } catch (Exception e) { Log.e(TAG, "Error on getting suggestions " + e.getMessage()); } } }); } }); // Initiate the asynchronous call mLocator.loadAsync(); } |
long method | long method | t | t | t | 0 | 9139 | https://github.com/Esri/maps-app-android/blob/1af1f74ece08f678ce7de7bf173034d30e1cb100/maps-app/src/main/java/com/esri/android/mapsapp/MapFragment.java/#L735-L781 | 1 | 997 | 9139 | minor | ||
| 1369 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Job20LineHistoryEventEmitter extends HistoryEventEmitter { static List nonFinals = new LinkedList(); static List finals = new LinkedList(); Long originalSubmitTime = null; static { nonFinals.add(new JobSubmittedEventEmitter()); nonFinals.add(new JobPriorityChangeEventEmitter()); nonFinals.add(new JobStatusChangedEventEmitter()); nonFinals.add(new JobInitedEventEmitter()); nonFinals.add(new JobInfoChangeEventEmitter()); finals.add(new JobUnsuccessfulCompletionEventEmitter()); finals.add(new JobFinishedEventEmitter()); } Job20LineHistoryEventEmitter() { super(); } static private class JobSubmittedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String submitTime = line.get("SUBMIT_TIME"); String jobConf = line.get("JOBCONF"); String user = line.get("USER"); if (user == null) { user = "nulluser"; } String jobName = line.get("JOBNAME"); String jobQueueName = line.get("JOB_QUEUE");// could be null String workflowId = line.get("WORKFLOW_ID"); if (workflowId == null) { workflowId = ""; } String workflowName = line.get("WORKFLOW_NAME"); if (workflowName == null) { workflowName = ""; } String workflowNodeName = line.get("WORKFLOW_NODE_NAME"); if (workflowNodeName == null) { workflowNodeName = ""; } String workflowAdjacencies = line.get("WORKFLOW_ADJACENCIES"); if (workflowAdjacencies == null) { workflowAdjacencies = ""; } String workflowTags = line.get("WORKFLOW_TAGS"); if (workflowTags == null) { workflowTags = ""; } if (submitTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; that.originalSubmitTime = Long.parseLong(submitTime); Map jobACLs = new HashMap(); return new JobSubmittedEvent(jobID, jobName, user, that.originalSubmitTime, jobConf, jobACLs, jobQueueName, workflowId, workflowName, workflowNodeName, workflowAdjacencies, workflowTags); } return null; } } static private class JobPriorityChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { JobID jobID = JobID.forName(jobIDName); if (jobIDName == null) { return null; } String priority = line.get("JOB_PRIORITY"); if (priority != null) { return new JobPriorityChangeEvent(jobID, JobPriority.valueOf(priority)); } return null; } } static private class JobInitedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); String status = line.get("JOB_STATUS"); String totalMaps = line.get("TOTAL_MAPS"); String totalReduces = line.get("TOTAL_REDUCES"); String uberized = line.get("UBERIZED"); if (launchTime != null && totalMaps != null && totalReduces != null) { return new JobInitedEvent(jobID, Long.parseLong(launchTime), Integer .parseInt(totalMaps), Integer.parseInt(totalReduces), status, Boolean.parseBoolean(uberized)); } return null; } } static private class JobStatusChangedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String status = line.get("JOB_STATUS"); if (status != null) { return new JobStatusChangedEvent(jobID, status); } return null; } } static private class JobInfoChangeEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String launchTime = line.get("LAUNCH_TIME"); if (launchTime != null) { Job20LineHistoryEventEmitter that = (Job20LineHistoryEventEmitter) thatg; return new JobInfoChangeEvent(jobID, that.originalSubmitTime, Long .parseLong(launchTime)); } return null; } } static private class JobUnsuccessfulCompletionEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); if (status != null && !status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobUnsuccessfulCompletionEvent(jobID, Long .parseLong(finishTime), Integer.parseInt(finishedMaps), Integer .parseInt(finishedReduces), -1, -1, -1, -1, status); } return null; } } static private class JobFinishedEventEmitter extends SingleEventEmitter { HistoryEvent maybeEmitEvent(ParsedLine line, String jobIDName, HistoryEventEmitter thatg) { if (jobIDName == null) { return null; } JobID jobID = JobID.forName(jobIDName); String finishTime = line.get("FINISH_TIME"); String status = line.get("JOB_STATUS"); String finishedMaps = line.get("FINISHED_MAPS"); String finishedReduces = line.get("FINISHED_REDUCES"); String failedMaps = line.get("FAILED_MAPS"); String failedReduces = line.get("FAILED_REDUCES"); String counters = line.get("COUNTERS"); if (status != null && status.equalsIgnoreCase("success") && finishTime != null && finishedMaps != null && finishedReduces != null) { return new JobFinishedEvent(jobID, Long.parseLong(finishTime), Integer .parseInt(finishedMaps), Integer.parseInt(finishedReduces), Integer .parseInt(failedMaps), Integer.parseInt(failedReduces), -1, -1, null, null, maybeParseCounters(counters)); } return null; } } @Override List finalSEEs() { return finals; } @Override List nonFinalSEEs() { return nonFinals; } } |
data class | long method, data class | t | t | t | long method | 0 | 10791 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Job20LineHistoryEventEmitter.java/#L39-L277 | 1 | 1369 | 10791 | minor | |
| 1657 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11601 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 1 | 1657 | 11601 | minor | |
| 1933 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
long method | long method | t | t | t | 0 | 12457 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 1933 | 12457 | minor | ||
| 2128 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private TtmlRegion parseRegionAttributes( XmlPullParser xmlParser, CellResolution cellResolution, TtsExtent ttsExtent) { String regionId = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_ID); if (regionId == null) { return null; } float position; float line; String regionOrigin = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_ORIGIN); if (regionOrigin != null) { Matcher originPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionOrigin); Matcher originPixelMatcher = PIXEL_COORDINATES.matcher(regionOrigin); if (originPercentageMatcher.matches()) { try { position = Float.parseFloat(originPercentageMatcher.group(1)) / 100f; line = Float.parseFloat(originPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else if (originPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int width = Integer.parseInt(originPixelMatcher.group(1)); int height = Integer.parseInt(originPixelMatcher.group(2)); // Convert pixel values to fractions. position = width / (float) ttsExtent.width; line = height / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported origin: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an origin"); return null; // TODO: Should default to top left as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Origin is omitted. Default to top left. // position = 0; // line = 0; } float width; float height; String regionExtent = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_EXTENT); if (regionExtent != null) { Matcher extentPercentageMatcher = PERCENTAGE_COORDINATES.matcher(regionExtent); Matcher extentPixelMatcher = PIXEL_COORDINATES.matcher(regionExtent); if (extentPercentageMatcher.matches()) { try { width = Float.parseFloat(extentPercentageMatcher.group(1)) / 100f; height = Float.parseFloat(extentPercentageMatcher.group(2)) / 100f; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else if (extentPixelMatcher.matches()) { if (ttsExtent == null) { Log.w(TAG, "Ignoring region with missing tts:extent: " + regionOrigin); return null; } try { int extentWidth = Integer.parseInt(extentPixelMatcher.group(1)); int extentHeight = Integer.parseInt(extentPixelMatcher.group(2)); // Convert pixel values to fractions. width = extentWidth / (float) ttsExtent.width; height = extentHeight / (float) ttsExtent.height; } catch (NumberFormatException e) { Log.w(TAG, "Ignoring region with malformed extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region with unsupported extent: " + regionOrigin); return null; } } else { Log.w(TAG, "Ignoring region without an extent"); return null; // TODO: Should default to extent of parent as below in this case, but need to fix // https://github.com/google/ExoPlayer/issues/2953 first. // Extent is omitted. Default to extent of parent. // width = 1; // height = 1; } @Cue.AnchorType int lineAnchor = Cue.ANCHOR_TYPE_START; String displayAlign = XmlPullParserUtil.getAttributeValue(xmlParser, TtmlNode.ATTR_TTS_DISPLAY_ALIGN); if (displayAlign != null) { switch (Util.toLowerInvariant(displayAlign)) { case "center": lineAnchor = Cue.ANCHOR_TYPE_MIDDLE; line += height / 2; break; case "after": lineAnchor = Cue.ANCHOR_TYPE_END; line += height; break; default: // Default "before" case. Do nothing. break; } } float regionTextHeight = 1.0f / cellResolution.rows; return new TtmlRegion( regionId, position, line, /* lineType= */ Cue.LINE_TYPE_FRACTION, lineAnchor, width, /* textSizeType= */ Cue.TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, /* textSize= */ regionTextHeight); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13224 | https://github.com/google/ExoPlayer/blob/4bc79c9465abd00e29ff576c5f7a7517be632f5a/library/core/src/main/java/com/google/android/exoplayer2/text/ttml/TtmlDecoder.java/#L311-L434 | 2 | 2128 | 13224 | major | ||
| 2306 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean optimizeForGoal(ClusterModel clusterModel, Goal goal, GoalViolations goalViolations, Set excludedBrokersForLeadership, Set excludedBrokersForReplicaMove) throws KafkaCruiseControlException { if (clusterModel.topics().isEmpty()) { LOG.info("Skipping goal violation detection because the cluster model does not have any topic."); return false; } Map> initReplicaDistribution = clusterModel.getReplicaDistribution(); Map initLeaderDistribution = clusterModel.getLeaderDistribution(); try { goal.optimize(clusterModel, new HashSet<>(), new OptimizationOptions(excludedTopics(clusterModel), excludedBrokersForLeadership, excludedBrokersForReplicaMove)); } catch (OptimizationFailureException ofe) { // An OptimizationFailureException indicates (1) a hard goal violation that cannot be fixed typically due to // lack of physical hardware (e.g. insufficient number of racks to satisfy rack awareness, insufficient number // of brokers to satisfy Replica Capacity Goal, or insufficient number of resources to satisfy resource // capacity goals), or (2) a failure to move offline replicas away from dead brokers/disks. goalViolations.addViolation(goal.name(), false); return true; } Set proposals = AnalyzerUtils.getDiff(initReplicaDistribution, initLeaderDistribution, clusterModel); LOG.trace("{} generated {} proposals", goal.name(), proposals.size()); if (!proposals.isEmpty()) { // A goal violation that can be optimized by applying the generated proposals. goalViolations.addViolation(goal.name(), true); return true; } else { // The goal is already satisfied. return false; } } |
long method | 1. long method | t | t | t | 0 | 14069 | https://github.com/linkedin/cruise-control/blob/d35af1b6d5a87046e6cd173948755a1e50faa531/cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/detector/GoalViolationDetector.java/#L217-L251 | 1 | 2306 | 14069 | minor | ||
| 355 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | data class | t | t | t | 0 | 3668 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 355 | 3668 | major | ||
| 5691 | YES I found bad smells The bad smells are: 1. Blob, 2. Long method | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | Blob, 2 Long method | t | f | t | . Blob | 0 | 12087 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5691 | 12087 | critical | |
| 945 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void widgetSelected( SelectionEvent e ) { Object widget = e.widget; if ( widget == btnVisible ) { // Notify Listeners that a change has occurred in the value fireValueChangedEvent( GanttLineAttributesComposite.VISIBILITY_CHANGED_EVENT, Boolean.valueOf( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED ), ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED ) ? ChartUIExtensionUtil.PROPERTY_UNSET : ChartUIExtensionUtil.PROPERTY_UPDATE ); // Notification may cause this class disposed if ( isDisposed( ) ) { return; } // Enable/Disable UI Elements boolean bEnableUI = context.getUIFactory( ).canEnableUI( btnVisible ); if ( bEnableStyles ) { lblStyle.setEnabled( bEnableUI ); cmbStyle.setEnabled( bEnableUI ); } if ( bEnableWidths ) { lblWidth.setEnabled( bEnableUI ); iscWidth.setEnabled( bEnableUI ); } if ( bEnableColor ) { lblColor.setEnabled( bEnableUI ); cmbColor.setEnabled( bEnableUI ); } } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 8480 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/GanttLineAttributesComposite.java/#L365-L398 | 1 | 945 | 8480 | minor | |
| 587 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected Context getContinuationContext(Name n) throws NamingException { Object obj = lookup(n.get(0)); CannotProceedException cpe = new CannotProceedException(); cpe.setResolvedObj(obj); cpe.setEnvironment(myEnv); return NamingManager.getContinuationContext(cpe); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 5854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java/#L195-L201 | 2 | 587 | 5854 | minor | |
| 371 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { if (getLog().isDebugEnabled()) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); } continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 3852 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/tooling/maven/camel-maven-plugin/src/main/java/org/apache/camel/maven/RunMojo.java/#L734-L761 | 2 | 371 | 3852 | minor | ||
| 5714 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12783 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 1 | 5714 | 12783 | critical | ||
| 249 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class CreditBureauData { private final long creditBureauId; private final String creditBureauName; private final String country; private final String productName; private final String creditBureauSummary; private final long implementationKey; private CreditBureauData(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { this.creditBureauId = creditBureauId; this.creditBureauName = creditBureauName; this.country = country; this.productName = productName; this.creditBureauSummary = creditBureauSummary; this.implementationKey = implementationKey; } public static CreditBureauData instance(final long creditBureauId, final String creditBureauName, final String country, final String productName, final String creditBureauSummary, final long implementationKey) { return new CreditBureauData(creditBureauId, creditBureauName, country, productName, creditBureauSummary, implementationKey); } public String getCreditBureauSummary() { return this.creditBureauSummary; } public long getCreditBureauId() { return this.creditBureauId; } public String getCreditBureauName() { return this.creditBureauName; } public String getCountry() { return this.country; } public String getProductName() { return this.productName; } public long getImplementationKey() { return this.implementationKey; } } |
data class | data class | t | t | t | 0 | 2663 | https://github.com/apache/fineract/blob/210e380df3ca5c74c8c2fa09e7fe1cffdb87e20a/fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/data/CreditBureauData.java/#L21-L77 | 1 | 249 | 2663 | major | ||
| 759 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReportInstance extends AbstractDTOBase { private String id; private ReportStatusEnum status; private String url; private String ownerId; private Boolean hasDetailRows; private ZonedDateTime completionDate; private ZonedDateTime requestDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public ReportStatusEnum getStatus() { return status; } public void setStatus(ReportStatusEnum status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public Boolean getHasDetailRows() { return hasDetailRows; } public void setHasDetailRows(Boolean hasDetailRows) { this.hasDetailRows = hasDetailRows; } public ZonedDateTime getCompletionDate() { return completionDate; } public void setCompletionDate(ZonedDateTime completionDate) { this.completionDate = completionDate; } public ZonedDateTime getRequestDate() { return requestDate; } public void setRequestDate(ZonedDateTime requestDate) { this.requestDate = requestDate; } } |
data class | 1. data class | t | t | t | 0 | 7066 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/ReportInstance.java/#L26-L91 | 1 | 759 | 7066 | critical | ||
| 2069 | YES I found bad smells the bad smells are: 1. Long class 2. Duplicate code (in methods setTargetUri and getTargetUris) 3. Temporary fields (in methods getTargetUri and getTargetUris) 4. Data class (all getter and setter methods with no logic or manipulation of data) 5. Misplaced field (field flowRefreshed could potentially be better placed in RemoteProcessGroupContentsDTO class) 6. Long parameter list (constructor with multiple parameters) 7. Feature envy (methods in RemoteProcessGroupContentsDTO class that could potentially be moved to this class) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlType(name = "remoteProcessGroup") public class RemoteProcessGroupDTO extends ComponentDTO { private String targetUri; private String targetUris; private Boolean targetSecure; private String name; private String comments; private String communicationsTimeout; private String yieldDuration; private String transportProtocol; private String localNetworkInterface; private String proxyHost; private Integer proxyPort; private String proxyUser; private String proxyPassword; private Collection authorizationIssues; private Collection validationErrors; private Boolean transmitting; private Integer inputPortCount; private Integer outputPortCount; private Integer activeRemoteInputPortCount; private Integer inactiveRemoteInputPortCount; private Integer activeRemoteOutputPortCount; private Integer inactiveRemoteOutputPortCount; private Date flowRefreshed; private RemoteProcessGroupContentsDTO contents; public RemoteProcessGroupDTO() { super(); } public RemoteProcessGroupDTO(final RemoteProcessGroupDTO toCopy) { setId(toCopy.getId()); setPosition(toCopy.getPosition()); targetUri = toCopy.getTargetUri(); name = toCopy.getName(); } public void setTargetUri(final String targetUri) { this.targetUri = targetUri; } /** * @return target uri of this remote process group. * If target uri is not set, but uris are set, then returns the first url in the urls. * If neither target uri nor uris are set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uri is not set, but uris are set, then returns the first url in the urls." + " If neither target uri nor uris are set, then returns null." ) public String getTargetUri() { if (targetUri == null || targetUri.length() == 0) { synchronized (this) { if (targetUri == null || targetUri.length() == 0) { if (targetUris != null && targetUris.length() > 0) { if (targetUris.indexOf(',') > -1) { targetUri = targetUris.substring(0, targetUris.indexOf(',')); } else { targetUri = targetUris; } } } } } return this.targetUri; } public void setTargetUris(String targetUris) { this.targetUris = targetUris; } /** * @return target uris of this remote process group * If targetUris was not set but target uri was set, then returns a collection containing the single uri. * If neither target uris nor uri were set, then returns null. */ @ApiModelProperty( value = "The target URI of the remote process group." + " If target uris is not set but target uri is set," + " then returns a collection containing the single target uri." + " If neither target uris nor uris are set, then returns null." ) public String getTargetUris() { if (targetUris == null || targetUris.length() == 0) { synchronized (this) { if (targetUris == null || targetUris.length() == 0) { targetUris = targetUri; } } } return this.targetUris; } /** * @param name of this remote process group */ @ApiModelProperty( value = "The name of the remote process group." ) public void setName(final String name) { this.name = name; } public String getName() { return this.name; } /** * @return Comments for this remote process group */ @ApiModelProperty( value = "The comments for the remote process group." ) public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } /** * @return any remote authorization issues for this remote process group */ @ApiModelProperty( value = "Any remote authorization issues for the remote process group." ) public Collection getAuthorizationIssues() { return authorizationIssues; } public void setAuthorizationIssues(Collection authorizationIssues) { this.authorizationIssues = authorizationIssues; } /** * @return whether or not this remote process group is actively transmitting */ @ApiModelProperty( value = "Whether the remote process group is actively transmitting." ) public Boolean isTransmitting() { return transmitting; } public void setTransmitting(Boolean transmitting) { this.transmitting = transmitting; } /** * @return whether or not the target is running securely */ @ApiModelProperty( value = "Whether the target is running securely." ) public Boolean isTargetSecure() { return targetSecure; } public void setTargetSecure(Boolean targetSecure) { this.targetSecure = targetSecure; } /** * @return the time period used for the timeout when communicating with this RemoteProcessGroup */ @ApiModelProperty( value = "The time period used for the timeout when communicating with the target." ) public String getCommunicationsTimeout() { return communicationsTimeout; } public void setCommunicationsTimeout(String communicationsTimeout) { this.communicationsTimeout = communicationsTimeout; } /** * @return when yielding, this amount of time must elapse before this remote process group is scheduled again */ @ApiModelProperty( value = "When yielding, this amount of time must elapse before the remote process group is scheduled again." ) public String getYieldDuration() { return yieldDuration; } public void setYieldDuration(String yieldDuration) { this.yieldDuration = yieldDuration; } /** * @return number of active remote input ports */ @ApiModelProperty( value = "The number of active remote input ports." ) public Integer getActiveRemoteInputPortCount() { return activeRemoteInputPortCount; } public void setActiveRemoteInputPortCount(Integer activeRemoteInputPortCount) { this.activeRemoteInputPortCount = activeRemoteInputPortCount; } /** * @return number of inactive remote input ports */ @ApiModelProperty( value = "The number of inactive remote input ports." ) public Integer getInactiveRemoteInputPortCount() { return inactiveRemoteInputPortCount; } public void setInactiveRemoteInputPortCount(Integer inactiveRemoteInputPortCount) { this.inactiveRemoteInputPortCount = inactiveRemoteInputPortCount; } /** * @return number of active remote output ports */ @ApiModelProperty( value = "The number of active remote output ports." ) public Integer getActiveRemoteOutputPortCount() { return activeRemoteOutputPortCount; } public void setActiveRemoteOutputPortCount(Integer activeRemoteOutputPortCount) { this.activeRemoteOutputPortCount = activeRemoteOutputPortCount; } /** * @return number of inactive remote output ports */ @ApiModelProperty( value = "The number of inactive remote output ports." ) public Integer getInactiveRemoteOutputPortCount() { return inactiveRemoteOutputPortCount; } public void setInactiveRemoteOutputPortCount(Integer inactiveRemoteOutputPortCount) { this.inactiveRemoteOutputPortCount = inactiveRemoteOutputPortCount; } /** * @return number of Remote Input Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote input ports currently available on the target." ) public Integer getInputPortCount() { return inputPortCount; } public void setInputPortCount(Integer inputPortCount) { this.inputPortCount = inputPortCount; } /** * @return number of Remote Output Ports currently available in the remote NiFi instance */ @ApiModelProperty( value = "The number of remote output ports currently available on the target." ) public Integer getOutputPortCount() { return outputPortCount; } public void setOutputPortCount(Integer outputPortCount) { this.outputPortCount = outputPortCount; } /** * @return contents of this remote process group. Will contain available input/output ports */ @ApiModelProperty( value = "The contents of the remote process group. Will contain available input/output ports." ) public RemoteProcessGroupContentsDTO getContents() { return contents; } public void setContents(RemoteProcessGroupContentsDTO contents) { this.contents = contents; } /** * @return the flow for this remote group was last refreshed */ @XmlJavaTypeAdapter(DateTimeAdapter.class) @ApiModelProperty( value = "The timestamp when this remote process group was last refreshed.", dataType = "string" ) public Date getFlowRefreshed() { return flowRefreshed; } public void setFlowRefreshed(Date flowRefreshed) { this.flowRefreshed = flowRefreshed; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } @ApiModelProperty("The local network interface to send/receive data. If not specified, any local address is used. If clustered, all nodes must have an interface with this identifier.") public String getLocalNetworkInterface() { return localNetworkInterface; } public void setLocalNetworkInterface(String localNetworkInterface) { this.localNetworkInterface = localNetworkInterface; } @ApiModelProperty( "The validation errors for the remote process group. These validation errors represent the problems with the remote process group that must be resolved before it can transmit." ) public Collection getValidationErrors() { return validationErrors; } public void setValidationErrors(Collection validationErrors) { this.validationErrors = validationErrors; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getProxyUser() { return proxyUser; } public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String getProxyPassword() { return proxyPassword; } public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } } |
data class | Long class2 Duplicate code (in methods setTargetUri and getTargetUris)3 Temporary fields (in methods getTargetUri and getTargetUris)4 Data class (all getter and setter methods with no logic or manipulation of data)5 Misplaced field (field flowRefreshed could potentially be better placed in RemoteProcessGroupContentsDTO class)6 Long parameter list (constructor with multiple parameters)7 Feature envy (methods in RemoteProcessGroupContentsDTO class that could potentially be moved to this class) | t | f | t | 0 | 13004 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/RemoteProcessGroupDTO.java/#L30-L405 | 2 | 2069 | 13004 | major | ||
| 1549 | {"response": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BacktrackingBug325745TestLanguagePackageImpl extends EPackageImpl implements BacktrackingBug325745TestLanguagePackage { /** * * * @generated */ private EClass modelEClass = null; /** * * * @generated */ private EClass elementEClass = null; /** * * * @generated */ private EClass dataTypeEClass = null; /** * * * @generated */ private EClass expressionEClass = null; /** * * * @generated */ private EClass simpleTermEClass = null; /** * Creates an instance of the model Package, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * * * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.xtext.parser.unorderedGroups.backtrackingBug325745TestLanguage.BacktrackingBug325745TestLanguagePackage#eNS_URI * @see #init() * @generated */ private BacktrackingBug325745TestLanguagePackageImpl() { super(eNS_URI, BacktrackingBug325745TestLanguageFactory.eINSTANCE); } /** * * * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. * * This method is used to initialize {@link BacktrackingBug325745TestLanguagePackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * * * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BacktrackingBug325745TestLanguagePackage init() { if (isInited) return (BacktrackingBug325745TestLanguagePackage)EPackage.Registry.INSTANCE.getEPackage(BacktrackingBug325745TestLanguagePackage.eNS_URI); // Obtain or create and register package BacktrackingBug325745TestLanguagePackageImpl theBacktrackingBug325745TestLanguagePackage = (BacktrackingBug325745TestLanguagePackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof BacktrackingBug325745TestLanguagePackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new BacktrackingBug325745TestLanguagePackageImpl()); isInited = true; // Initialize simple dependencies EcorePackage.eINSTANCE.eClass(); // Create package meta-data objects theBacktrackingBug325745TestLanguagePackage.createPackageContents(); // Initialize created meta-data theBacktrackingBug325745TestLanguagePackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBacktrackingBug325745TestLanguagePackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BacktrackingBug325745TestLanguagePackage.eNS_URI, theBacktrackingBug325745TestLanguagePackage); return theBacktrackingBug325745TestLanguagePackage; } /** * * * @generated */ public EClass getModel() { return modelEClass; } /** * * * @generated */ public EReference getModel_Fields() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EClass getElement() { return elementEClass; } /** * * * @generated */ public EAttribute getElement_Name() { return (EAttribute)elementEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getElement_DataType() { return (EReference)elementEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EReference getElement_Expression() { return (EReference)elementEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getDataType() { return dataTypeEClass; } /** * * * @generated */ public EAttribute getDataType_BaseType() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getDataType_DefaultValue() { return (EAttribute)dataTypeEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EClass getExpression() { return expressionEClass; } /** * * * @generated */ public EAttribute getExpression_Prefix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EReference getExpression_Terms() { return (EReference)expressionEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getExpression_Postfix() { return (EAttribute)expressionEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EClass getSimpleTerm() { return simpleTermEClass; } /** * * * @generated */ public EAttribute getSimpleTerm_LineCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(0); } /** * * * @generated */ public EAttribute getSimpleTerm_CharCount() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(1); } /** * * * @generated */ public EAttribute getSimpleTerm_CharSet() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(2); } /** * * * @generated */ public EAttribute getSimpleTerm_RefChar() { return (EAttribute)simpleTermEClass.getEStructuralFeatures().get(3); } /** * * * @generated */ public BacktrackingBug325745TestLanguageFactory getBacktrackingBug325745TestLanguageFactory() { return (BacktrackingBug325745TestLanguageFactory)getEFactoryInstance(); } /** * * * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * * * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__FIELDS); elementEClass = createEClass(ELEMENT); createEAttribute(elementEClass, ELEMENT__NAME); createEReference(elementEClass, ELEMENT__DATA_TYPE); createEReference(elementEClass, ELEMENT__EXPRESSION); dataTypeEClass = createEClass(DATA_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__BASE_TYPE); createEAttribute(dataTypeEClass, DATA_TYPE__DEFAULT_VALUE); expressionEClass = createEClass(EXPRESSION); createEAttribute(expressionEClass, EXPRESSION__PREFIX); createEReference(expressionEClass, EXPRESSION__TERMS); createEAttribute(expressionEClass, EXPRESSION__POSTFIX); simpleTermEClass = createEClass(SIMPLE_TERM); createEAttribute(simpleTermEClass, SIMPLE_TERM__LINE_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_COUNT); createEAttribute(simpleTermEClass, SIMPLE_TERM__CHAR_SET); createEAttribute(simpleTermEClass, SIMPLE_TERM__REF_CHAR); } /** * * * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * * * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Obtain other dependent packages EcorePackage theEcorePackage = (EcorePackage)EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes and features; add operations and parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Fields(), this.getElement(), null, "fields", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getElement_Name(), theEcorePackage.getEString(), "name", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_DataType(), this.getDataType(), null, "dataType", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getElement_Expression(), this.getExpression(), null, "expression", null, 0, 1, Element.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataTypeEClass, DataType.class, "DataType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getDataType_BaseType(), theEcorePackage.getEString(), "baseType", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getDataType_DefaultValue(), theEcorePackage.getEString(), "defaultValue", null, 0, 1, DataType.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(expressionEClass, Expression.class, "Expression", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getExpression_Prefix(), theEcorePackage.getEString(), "prefix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getExpression_Terms(), this.getSimpleTerm(), null, "terms", null, 0, -1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getExpression_Postfix(), theEcorePackage.getEString(), "postfix", null, 0, 1, Expression.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(simpleTermEClass, SimpleTerm.class, "SimpleTerm", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getSimpleTerm_LineCount(), theEcorePackage.getEInt(), "lineCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharCount(), theEcorePackage.getEInt(), "charCount", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_CharSet(), theEcorePackage.getEString(), "charSet", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getSimpleTerm_RefChar(), theEcorePackage.getEString(), "refChar", null, 0, 1, SimpleTerm.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BacktrackingBug325745TestLanguagePackageImpl |
blob | Blob, Data Class | t | f | t | Data Class | 0 | 11262 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/unorderedGroups/backtrackingBug325745TestLanguage/impl/BacktrackingBug325745TestLanguagePackageImpl.java/#L28-L426 | 1 | 1549 | 11262 | major | |
| 449 | { "output": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // define symbols mPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.SQUARE, 0xFFFF0000, 20); mLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFFFF8800, 4); mFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.CROSS, 0x40FFA9A9, mLineSymbol); // inflate map view from layout mMapView = findViewById(R.id.mapView); // create a map with the Basemap Type topographic ArcGISMap map = new ArcGISMap(Basemap.Type.LIGHT_GRAY_CANVAS, 34.056295, -117.195800, 16); // set the map to be displayed in this view mMapView.setMap(map); mGraphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); // create a new sketch editor and add it to the map view mSketchEditor = new SketchEditor(); mMapView.setSketchEditor(mSketchEditor); // get buttons from layouts mPointButton = findViewById(R.id.pointButton); mMultiPointButton = findViewById(R.id.pointsButton); mPolylineButton = findViewById(R.id.polylineButton); mPolygonButton = findViewById(R.id.polygonButton); mFreehandLineButton = findViewById(R.id.freehandLineButton); mFreehandPolygonButton = findViewById(R.id.freehandPolygonButton); // add click listeners mPointButton.setOnClickListener(view -> createModePoint()); mMultiPointButton.setOnClickListener(view -> createModeMultipoint()); mPolylineButton.setOnClickListener(view -> createModePolyline()); mPolygonButton.setOnClickListener(view -> createModePolygon()); mFreehandLineButton.setOnClickListener(view -> createModeFreehandLine()); mFreehandPolygonButton.setOnClickListener(view -> createModeFreehandPolygon()); } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 4369 | https://github.com/Esri/arcgis-runtime-samples-android/blob/22b9a4c99c82a75a128b64703c0c1ffb2f9f5293/java/sketch-editor/src/main/java/com/esri/arcgisruntime/sample/sketcheditor/MainActivity.java/#L44-L83 | 1 | 449 | 4369 | major | |
| 1190 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10253 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1190 | 10253 | critical | |
| 1997 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @MultiMQAdminCmdMethod public Map resetOffset(ResetOffsetRequest resetOffsetRequest) { Map groupRollbackStats = Maps.newHashMap(); for (String consumerGroup : resetOffsetRequest.getConsumerGroupList()) { try { Map rollbackStatsMap = mqAdminExt.resetOffsetByTimestamp(resetOffsetRequest.getTopic(), consumerGroup, resetOffsetRequest.getResetTime(), resetOffsetRequest.isForce()); ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = consumerGroupRollBackStat.getRollbackStatsList(); for (Map.Entry rollbackStatsEntty : rollbackStatsMap.entrySet()) { RollbackStats rollbackStats = new RollbackStats(); rollbackStats.setRollbackOffset(rollbackStatsEntty.getValue()); rollbackStats.setQueueId(rollbackStatsEntty.getKey().getQueueId()); rollbackStats.setBrokerName(rollbackStatsEntty.getKey().getBrokerName()); rollbackStatsList.add(rollbackStats); } groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); } catch (MQClientException e) { if (ResponseCode.CONSUMER_NOT_ONLINE == e.getResponseCode()) { try { ConsumerGroupRollBackStat consumerGroupRollBackStat = new ConsumerGroupRollBackStat(true); List rollbackStatsList = mqAdminExt.resetOffsetByTimestampOld(consumerGroup, resetOffsetRequest.getTopic(), resetOffsetRequest.getResetTime(), true); consumerGroupRollBackStat.setRollbackStatsList(rollbackStatsList); groupRollbackStats.put(consumerGroup, consumerGroupRollBackStat); continue; } catch (Exception err) { logger.error("op=resetOffset_which_not_online_error", err); } } else { logger.error("op=resetOffset_error", e); } groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } catch (Exception e) { logger.error("op=resetOffset_error", e); groupRollbackStats.put(consumerGroup, new ConsumerGroupRollBackStat(false, e.getMessage())); } } return groupRollbackStats; } |
long method | long method | t | t | t | 0 | 12700 | https://github.com/apache/rocketmq-externals/blob/dba6eb0c997d5c325f26b3d1da9d739d927228dc/rocketmq-console/src/main/java/org/apache/rocketmq/console/service/impl/ConsumerServiceImpl.java/#L208-L251 | 1 | 1997 | 12700 | major | ||
| 2029 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 12807 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 2029 | 12807 | minor | ||
| 2582 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14956 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 2582 | 14956 | minor | |
| 5407 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
long method | blob, long method | t | t | t | blob | 0 | 15185 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 1 | 5407 | 15185 | major | |
| 1272 | {"result": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10573 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1272 | 10573 | minor | |
| 3236 | { "result": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Singleton public class StandardComponentInitializer { public static final String NAVIGATE_TO_FILE = "navigateToFile"; public static final String FULL_TEXT_SEARCH = "fullTextSearch"; public static final String PREVIEW_IMAGE = "previewImage"; public static final String FIND_ACTION = "findAction"; public static final String FORMAT = "format"; public static final String SAVE = "save"; public static final String COPY = "copy"; public static final String CUT = "cut"; public static final String PASTE = "paste"; public static final String UNDO = "undo"; public static final String REDO = "redo"; public static final String SWITCH_LEFT_TAB = "switchLeftTab"; public static final String SWITCH_RIGHT_TAB = "switchRightTab"; public static final String OPEN_RECENT_FILES = "openRecentFiles"; public static final String DELETE_ITEM = "deleteItem"; public static final String NEW_FILE = "newFile"; public static final String CREATE_PROJECT = "createProject"; public static final String IMPORT_PROJECT = "importProject"; public static final String CLOSE_ACTIVE_EDITOR = "closeActiveEditor"; public static final String SIGNATURE_HELP = "signatureHelp"; public static final String SOFT_WRAP = "softWrap"; public static final String RENAME = "renameResource"; public static final String SHOW_REFERENCE = "showReference"; public static final String SHOW_COMMANDS_PALETTE = "showCommandsPalette"; public static final String NEW_TERMINAL = "newTerminal"; public static final String OPEN_IN_TERMINAL = "openInTerminal"; public static final String PROJECT_EXPLORER_DISPLAYING_MODE = "projectExplorerDisplayingMode"; public static final String COMMAND_EXPLORER_DISPLAYING_MODE = "commandExplorerDisplayingMode"; public static final String FIND_RESULT_DISPLAYING_MODE = "findResultDisplayingMode"; public static final String EVENT_LOGS_DISPLAYING_MODE = "eventLogsDisplayingMode"; public static final String EDITOR_DISPLAYING_MODE = "editorDisplayingMode"; public static final String TERMINAL_DISPLAYING_MODE = "terminalDisplayingMode"; public static final String REVEAL_RESOURCE = "revealResourceInProjectTree"; public static final String COLLAPSE_ALL = "collapseAll"; public interface ParserResource extends ClientBundle { @Source("org/eclipse/che/ide/blank.svg") SVGResource samplesCategoryBlank(); } @Inject private EditorRegistry editorRegistry; @Inject private FileTypeRegistry fileTypeRegistry; @Inject private Resources resources; @Inject private KeyBindingAgent keyBinding; @Inject private ActionManager actionManager; @Inject private SaveAction saveAction; @Inject private SaveAllAction saveAllAction; @Inject private ShowPreferencesAction showPreferencesAction; @Inject private PreviewImageAction previewImageAction; @Inject private FindActionAction findActionAction; @Inject private NavigateToFileAction navigateToFileAction; @Inject @MainToolbar private ToolbarPresenter toolbarPresenter; @Inject private CutResourceAction cutResourceAction; @Inject private CopyResourceAction copyResourceAction; @Inject private PasteResourceAction pasteResourceAction; @Inject private DeleteResourceAction deleteResourceAction; @Inject private RenameItemAction renameItemAction; @Inject private SplitVerticallyAction splitVerticallyAction; @Inject private SplitHorizontallyAction splitHorizontallyAction; @Inject private CloseAction closeAction; @Inject private CloseAllAction closeAllAction; @Inject private CloseOtherAction closeOtherAction; @Inject private CloseAllExceptPinnedAction closeAllExceptPinnedAction; @Inject private ReopenClosedFileAction reopenClosedFileAction; @Inject private PinEditorTabAction pinEditorTabAction; @Inject private GoIntoAction goIntoAction; @Inject private EditFileAction editFileAction; @Inject private OpenFileAction openFileAction; @Inject private ShowHiddenFilesAction showHiddenFilesAction; @Inject private FormatterAction formatterAction; @Inject private UndoAction undoAction; @Inject private RedoAction redoAction; @Inject private UploadFileAction uploadFileAction; @Inject private UploadFolderAction uploadFolderAction; @Inject private DownloadProjectAction downloadProjectAction; @Inject private DownloadWsAction downloadWsAction; @Inject private DownloadResourceAction downloadResourceAction; @Inject private ImportProjectAction importProjectAction; @Inject private CreateProjectAction createProjectAction; @Inject private ConvertFolderToProjectAction convertFolderToProjectAction; @Inject private FullTextSearchAction fullTextSearchAction; @Inject private NewFolderAction newFolderAction; @Inject private NewFileAction newFileAction; @Inject private NewXmlFileAction newXmlFileAction; @Inject private ImageViewerProvider imageViewerProvider; @Inject private ProjectConfigurationAction projectConfigurationAction; @Inject private ExpandEditorAction expandEditorAction; @Inject private CompleteAction completeAction; @Inject private SwitchPreviousEditorAction switchPreviousEditorAction; @Inject private SwitchNextEditorAction switchNextEditorAction; @Inject private HotKeysListAction hotKeysListAction; @Inject private OpenRecentFilesAction openRecentFilesAction; @Inject private ClearRecentListAction clearRecentFilesAction; @Inject private CloseActiveEditorAction closeActiveEditorAction; @Inject private MessageLoaderResources messageLoaderResources; @Inject private EditorResources editorResources; @Inject private PopupResources popupResources; @Inject private ShowReferenceAction showReferenceAction; @Inject private RevealResourceAction revealResourceAction; @Inject private RefreshPathAction refreshPathAction; @Inject private LinkWithEditorAction linkWithEditorAction; @Inject private ShowToolbarAction showToolbarAction; @Inject private SignatureHelpAction signatureHelpAction; @Inject private MaximizePartAction maximizePartAction; @Inject private HidePartAction hidePartAction; @Inject private RestorePartAction restorePartAction; @Inject private ShowCommandsPaletteAction showCommandsPaletteAction; @Inject private SoftWrapAction softWrapAction; @Inject private StartWorkspaceAction startWorkspaceAction; @Inject private StopWorkspaceAction stopWorkspaceAction; @Inject private ShowWorkspaceStatusAction showWorkspaceStatusAction; @Inject private ShowRuntimeInfoAction showRuntimeInfoAction; @Inject private RunCommandAction runCommandAction; @Inject private NewTerminalAction newTerminalAction; @Inject private ReRunProcessAction reRunProcessAction; @Inject private StopProcessAction stopProcessAction; @Inject private CloseConsoleAction closeConsoleAction; @Inject private DisplayMachineOutputAction displayMachineOutputAction; @Inject private PreviewSSHAction previewSSHAction; @Inject private ShowConsoleTreeAction showConsoleTreeAction; @Inject private AddToFileWatcherExcludesAction addToFileWatcherExcludesAction; @Inject private RemoveFromFileWatcherExcludesAction removeFromFileWatcherExcludesAction; @Inject private DevModeSetUpAction devModeSetUpAction; @Inject private DevModeOffAction devModeOffAction; @Inject private CollapseAllAction collapseAllAction; @Inject private PerspectiveManager perspectiveManager; @Inject private CommandsExplorerDisplayingModeAction commandsExplorerDisplayingModeAction; @Inject private ProjectExplorerDisplayingModeAction projectExplorerDisplayingModeAction; @Inject private EventLogsDisplayingModeAction eventLogsDisplayingModeAction; @Inject private FindResultDisplayingModeAction findResultDisplayingModeAction; @Inject private EditorDisplayingModeAction editorDisplayingModeAction; @Inject private TerminalDisplayingModeAction terminalDisplayingModeAction; @Inject private RenameCommandAction renameCommandAction; @Inject private MoveCommandAction moveCommandAction; @Inject private OpenInTerminalAction openInTerminalAction; @Inject private FreeDiskSpaceStatusBarAction freeDiskSpaceStatusBarAction; @Inject @Named("XMLFileType") private FileType xmlFile; @Inject @Named("TXTFileType") private FileType txtFile; @Inject @Named("JsonFileType") private FileType jsonFile; @Inject @Named("MDFileType") private FileType mdFile; @Inject @Named("PNGFileType") private FileType pngFile; @Inject @Named("BMPFileType") private FileType bmpFile; @Inject @Named("GIFFileType") private FileType gifFile; @Inject @Named("ICOFileType") private FileType iconFile; @Inject @Named("SVGFileType") private FileType svgFile; @Inject @Named("JPEFileType") private FileType jpeFile; @Inject @Named("JPEGFileType") private FileType jpegFile; @Inject @Named("JPGFileType") private FileType jpgFile; @Inject private CommandEditorProvider commandEditorProvider; @Inject @Named("CommandFileType") private FileType commandFileType; @Inject private ProjectConfigSynchronized projectConfigSynchronized; @Inject private TreeResourceRevealer treeResourceRevealer; // just to work with it @Inject private TerminalInitializer terminalInitializer; /** Instantiates {@link StandardComponentInitializer} an creates standard content. */ @Inject public StandardComponentInitializer( IconRegistry iconRegistry, MachineResources machineResources, StandardComponentInitializer.ParserResource parserResource) { iconRegistry.registerIcon( new Icon(BLANK_CATEGORY + ".samples.category.icon", parserResource.samplesCategoryBlank())); iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine())); machineResources.getCss().ensureInjected(); } public void initialize() { messageLoaderResources.Css().ensureInjected(); editorResources.editorCss().ensureInjected(); popupResources.popupStyle().ensureInjected(); fileTypeRegistry.registerFileType(xmlFile); fileTypeRegistry.registerFileType(txtFile); fileTypeRegistry.registerFileType(jsonFile); fileTypeRegistry.registerFileType(mdFile); fileTypeRegistry.registerFileType(pngFile); editorRegistry.registerDefaultEditor(pngFile, imageViewerProvider); fileTypeRegistry.registerFileType(bmpFile); editorRegistry.registerDefaultEditor(bmpFile, imageViewerProvider); fileTypeRegistry.registerFileType(gifFile); editorRegistry.registerDefaultEditor(gifFile, imageViewerProvider); fileTypeRegistry.registerFileType(iconFile); editorRegistry.registerDefaultEditor(iconFile, imageViewerProvider); fileTypeRegistry.registerFileType(svgFile); editorRegistry.registerDefaultEditor(svgFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpeFile); editorRegistry.registerDefaultEditor(jpeFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpegFile); editorRegistry.registerDefaultEditor(jpegFile, imageViewerProvider); fileTypeRegistry.registerFileType(jpgFile); editorRegistry.registerDefaultEditor(jpgFile, imageViewerProvider); fileTypeRegistry.registerFileType(commandFileType); editorRegistry.registerDefaultEditor(commandFileType, commandEditorProvider); // Workspace (New Menu) DefaultActionGroup workspaceGroup = (DefaultActionGroup) actionManager.getAction(GROUP_WORKSPACE); actionManager.registerAction(IMPORT_PROJECT, importProjectAction); workspaceGroup.add(importProjectAction); actionManager.registerAction(CREATE_PROJECT, createProjectAction); workspaceGroup.add(createProjectAction); actionManager.registerAction("downloadWsAsZipAction", downloadWsAction); workspaceGroup.add(downloadWsAction); workspaceGroup.addSeparator(); workspaceGroup.add(startWorkspaceAction); workspaceGroup.add(stopWorkspaceAction); workspaceGroup.add(showWorkspaceStatusAction); // Project (New Menu) DefaultActionGroup projectGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROJECT); DefaultActionGroup newGroup = new DefaultActionGroup("New", true, actionManager); newGroup.getTemplatePresentation().setDescription("Create..."); newGroup .getTemplatePresentation() .setImageElement(new SVGImage(resources.newResource()).getElement()); actionManager.registerAction(GROUP_FILE_NEW, newGroup); projectGroup.add(newGroup); newGroup.addSeparator(); actionManager.registerAction(NEW_FILE, newFileAction); newGroup.addAction(newFileAction, Constraints.FIRST); actionManager.registerAction("newFolder", newFolderAction); newGroup.addAction(newFolderAction, new Constraints(AFTER, NEW_FILE)); newGroup.addSeparator(); actionManager.registerAction("newXmlFile", newXmlFileAction); newXmlFileAction .getTemplatePresentation() .setImageElement(new SVGImage(xmlFile.getImage()).getElement()); newGroup.addAction(newXmlFileAction); actionManager.registerAction("uploadFile", uploadFileAction); projectGroup.add(uploadFileAction); actionManager.registerAction("uploadFolder", uploadFolderAction); projectGroup.add(uploadFolderAction); actionManager.registerAction("convertFolderToProject", convertFolderToProjectAction); projectGroup.add(convertFolderToProjectAction); actionManager.registerAction("downloadAsZipAction", downloadProjectAction); projectGroup.add(downloadProjectAction); actionManager.registerAction("showHideHiddenFiles", showHiddenFilesAction); projectGroup.add(showHiddenFilesAction); projectGroup.addSeparator(); actionManager.registerAction("projectConfiguration", projectConfigurationAction); projectGroup.add(projectConfigurationAction); DefaultActionGroup saveGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("saveGroup", saveGroup); actionManager.registerAction(SAVE, saveAction); saveGroup.addSeparator(); saveGroup.add(saveAction); // Edit (New Menu) DefaultActionGroup editGroup = (DefaultActionGroup) actionManager.getAction(GROUP_EDIT); DefaultActionGroup recentGroup = new DefaultActionGroup(RECENT_GROUP_ID, true, actionManager); actionManager.registerAction(GROUP_RECENT_FILES, recentGroup); actionManager.registerAction("clearRecentList", clearRecentFilesAction); recentGroup.addSeparator(); recentGroup.add(clearRecentFilesAction, LAST); editGroup.add(recentGroup); actionManager.registerAction(OPEN_RECENT_FILES, openRecentFilesAction); editGroup.add(openRecentFilesAction); actionManager.registerAction(CLOSE_ACTIVE_EDITOR, closeActiveEditorAction); editGroup.add(closeActiveEditorAction); actionManager.registerAction(FORMAT, formatterAction); editGroup.add(formatterAction); editGroup.add(saveAction); actionManager.registerAction(UNDO, undoAction); editGroup.add(undoAction); actionManager.registerAction(REDO, redoAction); editGroup.add(redoAction); actionManager.registerAction(SOFT_WRAP, softWrapAction); editGroup.add(softWrapAction); actionManager.registerAction(CUT, cutResourceAction); editGroup.add(cutResourceAction); actionManager.registerAction(COPY, copyResourceAction); editGroup.add(copyResourceAction); actionManager.registerAction(PASTE, pasteResourceAction); editGroup.add(pasteResourceAction); actionManager.registerAction(RENAME, renameItemAction); editGroup.add(renameItemAction); actionManager.registerAction(DELETE_ITEM, deleteResourceAction); editGroup.add(deleteResourceAction); actionManager.registerAction(FULL_TEXT_SEARCH, fullTextSearchAction); editGroup.add(fullTextSearchAction); editGroup.addSeparator(); editGroup.add(switchPreviousEditorAction); editGroup.add(switchNextEditorAction); // Assistant (New Menu) DefaultActionGroup assistantGroup = (DefaultActionGroup) actionManager.getAction(GROUP_ASSISTANT); actionManager.registerAction(PREVIEW_IMAGE, previewImageAction); assistantGroup.add(previewImageAction); actionManager.registerAction(FIND_ACTION, findActionAction); assistantGroup.add(findActionAction); actionManager.registerAction("hotKeysList", hotKeysListAction); assistantGroup.add(hotKeysListAction); assistantGroup.addSeparator(); // Switching of parts DefaultActionGroup toolWindowsGroup = new DefaultActionGroup("Tool Windows", true, actionManager); actionManager.registerAction(TOOL_WINDOWS_GROUP, toolWindowsGroup); actionManager.registerAction( PROJECT_EXPLORER_DISPLAYING_MODE, projectExplorerDisplayingModeAction); actionManager.registerAction(FIND_RESULT_DISPLAYING_MODE, findResultDisplayingModeAction); actionManager.registerAction(EVENT_LOGS_DISPLAYING_MODE, eventLogsDisplayingModeAction); actionManager.registerAction( COMMAND_EXPLORER_DISPLAYING_MODE, commandsExplorerDisplayingModeAction); actionManager.registerAction(EDITOR_DISPLAYING_MODE, editorDisplayingModeAction); actionManager.registerAction(TERMINAL_DISPLAYING_MODE, terminalDisplayingModeAction); toolWindowsGroup.add(projectExplorerDisplayingModeAction, FIRST); toolWindowsGroup.add( eventLogsDisplayingModeAction, new Constraints(AFTER, PROJECT_EXPLORER_DISPLAYING_MODE)); toolWindowsGroup.add( findResultDisplayingModeAction, new Constraints(AFTER, EVENT_LOGS_DISPLAYING_MODE)); toolWindowsGroup.add( commandsExplorerDisplayingModeAction, new Constraints(AFTER, FIND_RESULT_DISPLAYING_MODE)); toolWindowsGroup.add(editorDisplayingModeAction); toolWindowsGroup.add(terminalDisplayingModeAction); assistantGroup.add(toolWindowsGroup); assistantGroup.addSeparator(); actionManager.registerAction("callCompletion", completeAction); assistantGroup.add(completeAction); actionManager.registerAction("downloadItemAction", downloadResourceAction); actionManager.registerAction(NAVIGATE_TO_FILE, navigateToFileAction); assistantGroup.add(navigateToFileAction); assistantGroup.addSeparator(); actionManager.registerAction("devModeSetUpAction", devModeSetUpAction); actionManager.registerAction("devModeOffAction", devModeOffAction); assistantGroup.add(devModeSetUpAction); assistantGroup.add(devModeOffAction); // Compose Profile menu DefaultActionGroup profileGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PROFILE); actionManager.registerAction("showPreferences", showPreferencesAction); profileGroup.add(showPreferencesAction); // Compose Help menu DefaultActionGroup helpGroup = (DefaultActionGroup) actionManager.getAction(GROUP_HELP); helpGroup.addSeparator(); // Processes panel actions actionManager.registerAction("startWorkspace", startWorkspaceAction); actionManager.registerAction("stopWorkspace", stopWorkspaceAction); actionManager.registerAction("showWorkspaceStatus", showWorkspaceStatusAction); actionManager.registerAction("runCommand", runCommandAction); actionManager.registerAction("newTerminal", newTerminalAction); // Compose main context menu DefaultActionGroup resourceOperation = new DefaultActionGroup(actionManager); actionManager.registerAction("resourceOperation", resourceOperation); actionManager.registerAction("refreshPathAction", refreshPathAction); actionManager.registerAction("linkWithEditor", linkWithEditorAction); actionManager.registerAction("showToolbar", showToolbarAction); resourceOperation.addSeparator(); resourceOperation.add(previewImageAction); resourceOperation.add(showReferenceAction); resourceOperation.add(goIntoAction); resourceOperation.add(editFileAction); resourceOperation.add(saveAction); resourceOperation.add(cutResourceAction); resourceOperation.add(copyResourceAction); resourceOperation.add(pasteResourceAction); resourceOperation.add(renameItemAction); resourceOperation.add(deleteResourceAction); resourceOperation.addSeparator(); resourceOperation.add(downloadResourceAction); resourceOperation.add(refreshPathAction); resourceOperation.add(linkWithEditorAction); resourceOperation.add(collapseAllAction); resourceOperation.addSeparator(); resourceOperation.add(convertFolderToProjectAction); resourceOperation.addSeparator(); resourceOperation.addSeparator(); resourceOperation.add(addToFileWatcherExcludesAction); resourceOperation.add(removeFromFileWatcherExcludesAction); resourceOperation.addSeparator(); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_CONTEXT_MENU); mainContextMenuGroup.add(newGroup, FIRST); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(resourceOperation); mainContextMenuGroup.add(openInTerminalAction); actionManager.registerAction(OPEN_IN_TERMINAL, openInTerminalAction); DefaultActionGroup partMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_PART_MENU); partMenuGroup.add(maximizePartAction); partMenuGroup.add(hidePartAction); partMenuGroup.add(restorePartAction); partMenuGroup.add(showConsoleTreeAction); partMenuGroup.add(revealResourceAction); partMenuGroup.add(collapseAllAction); partMenuGroup.add(refreshPathAction); partMenuGroup.add(linkWithEditorAction); DefaultActionGroup toolbarControllerGroup = (DefaultActionGroup) actionManager.getAction(GROUP_TOOLBAR_CONTROLLER); toolbarControllerGroup.add(showToolbarAction); actionManager.registerAction("expandEditor", expandEditorAction); DefaultActionGroup rightMenuGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_MAIN_MENU); rightMenuGroup.add(expandEditorAction, FIRST); // Compose main toolbar DefaultActionGroup changeResourceGroup = new DefaultActionGroup(actionManager); actionManager.registerAction("changeResourceGroup", changeResourceGroup); actionManager.registerAction("editFile", editFileAction); actionManager.registerAction("goInto", goIntoAction); actionManager.registerAction(SHOW_REFERENCE, showReferenceAction); actionManager.registerAction(REVEAL_RESOURCE, revealResourceAction); actionManager.registerAction(COLLAPSE_ALL, collapseAllAction); actionManager.registerAction("openFile", openFileAction); actionManager.registerAction(SWITCH_LEFT_TAB, switchPreviousEditorAction); actionManager.registerAction(SWITCH_RIGHT_TAB, switchNextEditorAction); changeResourceGroup.add(cutResourceAction); changeResourceGroup.add(copyResourceAction); changeResourceGroup.add(pasteResourceAction); changeResourceGroup.add(deleteResourceAction); DefaultActionGroup mainToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_TOOLBAR); mainToolbarGroup.add(newGroup); mainToolbarGroup.add(saveGroup); mainToolbarGroup.add(changeResourceGroup); toolbarPresenter.bindMainGroup(mainToolbarGroup); DefaultActionGroup centerToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_CENTER_TOOLBAR); toolbarPresenter.bindCenterGroup(centerToolbarGroup); DefaultActionGroup rightToolbarGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_TOOLBAR); toolbarPresenter.bindRightGroup(rightToolbarGroup); actionManager.registerAction("showServers", showRuntimeInfoAction); // Consoles tree context menu group DefaultActionGroup consolesTreeContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_CONSOLES_TREE_CONTEXT_MENU); consolesTreeContextMenu.add(showRuntimeInfoAction); consolesTreeContextMenu.add(newTerminalAction); consolesTreeContextMenu.add(reRunProcessAction); consolesTreeContextMenu.add(stopProcessAction); consolesTreeContextMenu.add(closeConsoleAction); actionManager.registerAction("displayMachineOutput", displayMachineOutputAction); consolesTreeContextMenu.add(displayMachineOutputAction); actionManager.registerAction("previewSSH", previewSSHAction); consolesTreeContextMenu.add(previewSSHAction); // Editor context menu group DefaultActionGroup editorTabContextMenu = (DefaultActionGroup) actionManager.getAction(GROUP_EDITOR_TAB_CONTEXT_MENU); editorTabContextMenu.add(closeAction); actionManager.registerAction(CLOSE, closeAction); editorTabContextMenu.add(closeAllAction); actionManager.registerAction(CLOSE_ALL, closeAllAction); editorTabContextMenu.add(closeOtherAction); actionManager.registerAction(CLOSE_OTHER, closeOtherAction); editorTabContextMenu.add(closeAllExceptPinnedAction); actionManager.registerAction(CLOSE_ALL_EXCEPT_PINNED, closeAllExceptPinnedAction); editorTabContextMenu.addSeparator(); editorTabContextMenu.add(reopenClosedFileAction); actionManager.registerAction(REOPEN_CLOSED, reopenClosedFileAction); editorTabContextMenu.add(pinEditorTabAction); actionManager.registerAction(PIN_TAB, pinEditorTabAction); editorTabContextMenu.addSeparator(); actionManager.registerAction(SPLIT_HORIZONTALLY, splitHorizontallyAction); editorTabContextMenu.add(splitHorizontallyAction); actionManager.registerAction(SPLIT_VERTICALLY, splitVerticallyAction); editorTabContextMenu.add(splitVerticallyAction); actionManager.registerAction(SIGNATURE_HELP, signatureHelpAction); actionManager.registerAction(SHOW_COMMANDS_PALETTE, showCommandsPaletteAction); DefaultActionGroup runGroup = (DefaultActionGroup) actionManager.getAction(IdeActions.GROUP_RUN); runGroup.add(showCommandsPaletteAction); runGroup.add(newTerminalAction, FIRST); runGroup.addSeparator(); DefaultActionGroup editorContextMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_EDITOR_CONTEXT_MENU, editorContextMenuGroup); editorContextMenuGroup.add(saveAction); editorContextMenuGroup.add(undoAction); editorContextMenuGroup.add(redoAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(formatterAction); editorContextMenuGroup.add(softWrapAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(fullTextSearchAction); editorContextMenuGroup.add(closeActiveEditorAction); editorContextMenuGroup.addSeparator(); editorContextMenuGroup.add(revealResourceAction); DefaultActionGroup commandExplorerMenuGroup = new DefaultActionGroup(actionManager); actionManager.registerAction(GROUP_COMMAND_EXPLORER_CONTEXT_MENU, commandExplorerMenuGroup); actionManager.registerAction("renameCommand", renameCommandAction); commandExplorerMenuGroup.add(renameCommandAction); actionManager.registerAction("moveCommand", moveCommandAction); commandExplorerMenuGroup.add(moveCommandAction); DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup) actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(freeDiskSpaceStatusBarAction); // Define hot-keys keyBinding .getGlobal() .addKey(new KeyBuilder().action().alt().charCode('n').build(), NAVIGATE_TO_FILE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('F').build(), FULL_TEXT_SEARCH); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('A').build(), FIND_ACTION); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('L').build(), FORMAT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('c').build(), COPY); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('x').build(), CUT); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('v').build(), PASTE); keyBinding.getGlobal().addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F6).build(), RENAME); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F7).build(), SHOW_REFERENCE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_LEFT).build(), SWITCH_LEFT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.ARROW_RIGHT).build(), SWITCH_RIGHT_TAB); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('e').build(), OPEN_RECENT_FILES); keyBinding .getGlobal() .addKey(new KeyBuilder().charCode(KeyCodeMap.DELETE).build(), DELETE_ITEM); keyBinding.getGlobal().addKey(new KeyBuilder().action().alt().charCode('w').build(), SOFT_WRAP); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), NEW_TERMINAL); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().shift().charCode(KeyCodeMap.F12).build(), OPEN_IN_TERMINAL); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('N').build(), NEW_FILE); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('x').build(), CREATE_PROJECT); keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode('A').build(), IMPORT_PROJECT); keyBinding .getGlobal() .addKey(new KeyBuilder().shift().charCode(KeyCodeMap.F10).build(), SHOW_COMMANDS_PALETTE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('s').build(), SAVE); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('z').build(), UNDO); keyBinding.getGlobal().addKey(new KeyBuilder().action().charCode('y').build(), REDO); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().control().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } else { keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('1').build(), PROJECT_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('2').build(), EVENT_LOGS_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('3').build(), FIND_RESULT_DISPLAYING_MODE); keyBinding .getGlobal() .addKey( new KeyBuilder().action().alt().charCode('4').build(), COMMAND_EXPLORER_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('E').build(), EDITOR_DISPLAYING_MODE); keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('T').build(), TERMINAL_DISPLAYING_MODE); } keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_DOWN).build(), REVEAL_RESOURCE); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode(ARROW_UP).build(), COLLAPSE_ALL); if (UserAgent.isMac()) { keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().control().charCode('p').build(), SIGNATURE_HELP); } else { keyBinding .getGlobal() .addKey(new KeyBuilder().alt().charCode('w').build(), CLOSE_ACTIVE_EDITOR); keyBinding .getGlobal() .addKey(new KeyBuilder().action().charCode('p').build(), SIGNATURE_HELP); } final Map perspectives = perspectiveManager.getPerspectives(); if (perspectives.size() > 1) { // if registered perspectives will be more then 2 Main Menu -> Window // will appears and contains all of them as sub-menu final DefaultActionGroup windowMenu = new DefaultActionGroup("Window", true, actionManager); actionManager.registerAction("Window", windowMenu); final DefaultActionGroup mainMenu = (DefaultActionGroup) actionManager.getAction(GROUP_MAIN_MENU); mainMenu.add(windowMenu); for (Perspective perspective : perspectives.values()) { final BaseAction action = new BaseAction(perspective.getPerspectiveName()) { @Override public void actionPerformed(ActionEvent e) { perspectiveManager.setPerspectiveId(perspective.getPerspectiveId()); } }; actionManager.registerAction(perspective.getPerspectiveId(), action); windowMenu.add(action); } } } } |
data class | long method, data class | t | t | t | long method | 0 | 5427 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/core/StandardComponentInitializer.java/#L179-L1046 | 1 | 3236 | 5427 | critical | |
| 1279 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int specialStateTransition(int s, IntStream _input) throws NoViableAltException { TokenStream input = (TokenStream)_input; int _s = s; switch ( s ) { case 0 : int LA60_0 = input.LA(1); int index60_0 = input.index(); input.rewind(); s = -1; if ( (LA60_0==RULE_ID) ) {s = 1;} else if ( (LA60_0==14) ) {s = 2;} else if ( (LA60_0==39) && (synpred33_InternalXbaseWithAnnotations())) {s = 3;} else if ( ((LA60_0>=RULE_STRING && LA60_0<=RULE_DECIMAL)||(LA60_0>=18 && LA60_0<=19)||LA60_0==26||(LA60_0>=42 && LA60_0<=43)||LA60_0==48||LA60_0==55||LA60_0==59||LA60_0==61||(LA60_0>=65 && LA60_0<=67)||(LA60_0>=70 && LA60_0<=82)||LA60_0==84) ) {s = 4;} input.seek(index60_0); if ( s>=0 ) return s; break; case 1 : int LA60_1 = input.LA(1); int index60_1 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_1); if ( s>=0 ) return s; break; case 2 : int LA60_2 = input.LA(1); int index60_2 = input.index(); input.rewind(); s = -1; if ( (synpred33_InternalXbaseWithAnnotations()) ) {s = 3;} else if ( (true) ) {s = 4;} input.seek(index60_2); if ( s>=0 ) return s; break; } if (state.backtracking>0) {state.failed=true; return -1;} NoViableAltException nvae = new NoViableAltException(getDescription(), 60, _s, input); error(nvae); throw nvae; } |
long method | long method | t | t | t | 0 | 10593 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src-gen/org/eclipse/xtext/xbase/annotations/parser/antlr/internal/InternalXbaseWithAnnotationsParser.java/#L22612-L22671 | 1 | 1279 | 10593 | minor | ||
| 1490 | YES I found bad smells the bad smells: 1.Split temporary variable, 2.Long method, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, 10.Duplicate code, 11.Functional decomposition, 12.Long parameter list. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | Split temporary variable, 2Long method, 3Feature envy, 4Primitive obsession, 5Magic numbers, 6Inappropriate intimacy, 7Unnecessary temporary variables, 8Speculative generality, 9Nested loops, | t | f | t | .Split temporary variable, 3.Feature envy, 4.Primitive obsession, 5.Magic numbers, 6.Inappropriate intimacy, 7.Unnecessary temporary variables, 8.Speculative generality, 9.Nested loops, | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 2 | 1490 | 11110 | critical | |
| 1083 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "serialization-registration-type", namespace = "http://geode.apache.org/schema/cache", propOrder = {"serializers", "instantiators"}) @Experimental public class SerializationRegistrationType { @XmlElement(name = "serializer", namespace = "http://geode.apache.org/schema/cache") protected List serializers; @XmlElement(name = "instantiator", namespace = "http://geode.apache.org/schema/cache") protected List instantiators; /** * Gets the value of the serializer property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the serializer property. * * * For example, to add a new item, do as follows: * * * getSerializer().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Serializer } * * */ public List getSerializers() { if (serializers == null) { serializers = new ArrayList(); } return this.serializers; } /** * Gets the value of the instantiator property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the instantiator property. * * * For example, to add a new item, do as follows: * * * getInstantiator().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link SerializationRegistrationType.Instantiator } * * */ public List getInstantiators() { if (instantiators == null) { instantiators = new ArrayList(); } return this.instantiators; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Instantiator { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * </sequence> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"className"}) public static class Serializer { @XmlElement(name = "class-name", namespace = "http://geode.apache.org/schema/cache", required = true) protected String className; /** * Gets the value of the className property. * * possible object is * {@link String } * */ public String getClassName() { return className; } /** * Sets the value of the className property. * * allowed object is * {@link String } * */ public void setClassName(String value) { this.className = value; } } } |
data class | blob, data class | t | t | t | blob | 0 | 9689 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/SerializationRegistrationType.java/#L81-L286 | 1 | 1083 | 9689 | minor | |
| 3854 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | data class | t | t | t | 0 | 10010 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 3854 | 10010 | major | ||
| 3905 | {"response": "YES I found bad smells the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static public Object postUpdate(String itemName, String stateString) { ItemRegistry registry = ScriptServiceUtil.getItemRegistry(); EventPublisher publisher = ScriptServiceUtil.getEventPublisher(); if (publisher != null && registry != null) { try { Item item = registry.getItem(itemName); State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString); if (state != null) { publisher.post(ItemEventFactory.createStateEvent(itemName, state)); } else { LoggerFactory.getLogger(BusEvent.class).warn( "Cannot convert '{}' to a state type which item '{}' accepts: {}.", stateString, itemName, getAcceptedDataTypeNames(item)); } } catch (ItemNotFoundException e) { LoggerFactory.getLogger(BusEvent.class).warn("Item '{}' does not exist.", itemName); } } return null; } |
long method | 1. long method | t | t | t | 0 | 10223 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/model/org.eclipse.smarthome.model.script/src/org/eclipse/smarthome/model/script/actions/BusEvent.java/#L153-L172 | 1 | 3905 | 10223 | minor | ||
| 2527 | YES, I found bad smells the bad smells are: 1. Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand. 2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | Long method - The method contains a lot of lines and multiple levels of nesting, making it difficult to read and understand2 Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method | t | f | t | making it difficult to read and understand.2. Feature envy - The method is accessing data from multiple external objects and performing operations on them, indicating a potential design issue where the functionality should be placed within those objects instead of being separated in this method. | 0 | 14726 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 2 | 2527 | 14726 | major | |
| 1451 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void writeFinalRule(Writer writer, boolean isDst, AnnualTimeZoneRule rule, int fromRawOffset, int fromDSTSavings, long startTime) throws IOException{ DateTimeRule dtrule = toWallTimeRule(rule.getRule(), fromRawOffset, fromDSTSavings); // If the rule's mills in a day is out of range, adjust start time. // Olson tzdata supports 24:00 of a day, but VTIMEZONE does not. // See ticket#7008/#7518 int timeInDay = dtrule.getRuleMillisInDay(); if (timeInDay < 0) { startTime = startTime + (0 - timeInDay); } else if (timeInDay >= Grego.MILLIS_PER_DAY) { startTime = startTime - (timeInDay - (Grego.MILLIS_PER_DAY - 1)); } int toOffset = rule.getRawOffset() + rule.getDSTSavings(); switch (dtrule.getDateRuleType()) { case DateTimeRule.DOM: writeZonePropsByDOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), startTime, MAX_TIME); break; case DateTimeRule.DOW: writeZonePropsByDOW(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleWeekInMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_GEQ_DOM: writeZonePropsByDOW_GEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; case DateTimeRule.DOW_LEQ_DOM: writeZonePropsByDOW_LEQ_DOM(writer, isDst, rule.getName(), fromRawOffset + fromDSTSavings, toOffset, dtrule.getRuleMonth(), dtrule.getRuleDayOfMonth(), dtrule.getRuleDayOfWeek(), startTime, MAX_TIME); break; } } |
long method | 1. long method | t | t | t | 0 | 11000 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/VTimeZone.java/#L1661-L1695 | 1 | 1451 | 11000 | minor | ||
| 5401 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | blob, long method | t | t | t | blob | 0 | 15176 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/proxy/src/main/java/org/apache/accumulo/proxy/thrift/AccumuloProxy.java/#L126206-L126230 | 1 | 5401 | 15176 | minor | |
| 2168 | YES I found bad smells The bad smells are: 1. Long method 2. Redundant code 3. Feature envy 4. Comments to state the obvious 5. Magic numbers 6. Inconsistent naming conventions 7. Inconsistent formatting 8. Poor exception handling 9. Code duplication with slight variations | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void verifyRepository(RepositoryRequest request) throws AmbariException { URLStreamProvider usp = new URLStreamProvider(REPO_URL_CONNECT_TIMEOUT, REPO_URL_READ_TIMEOUT, null, null, null); usp.setSetupTruststoreForHttps(false); String repoName = request.getRepoName(); if (StringUtils.isEmpty(repoName)) { throw new IllegalArgumentException("repo_name is required to verify repository"); } String errorMessage = null; Exception e = null; String[] suffixes = configs.getRepoValidationSuffixes(request.getOsType()); for (String suffix : suffixes) { String formatted_suffix = String.format(suffix, repoName); String spec = request.getBaseUrl().trim(); // This logic is to identify if the end of baseurl has a slash ('/') and/or the beginning of suffix String (e.g. "/repodata/repomd.xml") // has a slash and they can form a good url. // e.g. "http://baseurl.com/" + "/repodata/repomd.xml" becomes "http://baseurl.com/repodata/repomd.xml" but not "http://baseurl.com//repodata/repomd.xml" if (spec.charAt(spec.length() - 1) != '/' && formatted_suffix.charAt(0) != '/') { spec = spec + "/" + formatted_suffix; } else if (spec.charAt(spec.length() - 1) == '/' && formatted_suffix.charAt(0) == '/') { spec = spec + formatted_suffix.substring(1); } else { spec = spec + formatted_suffix; } // if spec contains "file://" then check local file system. final String FILE_SCHEME = "file://"; if(spec.toLowerCase().startsWith(FILE_SCHEME)){ String filePath = spec.substring(FILE_SCHEME.length()); File f = new File(filePath); if(!f.exists()){ errorMessage = "Could not access base url . " + spec + " . "; e = new FileNotFoundException(errorMessage); break; } }else{ try { IOUtils.readLines(usp.readFrom(spec)); } catch (IOException ioe) { e = ioe; errorMessage = "Could not access base url . " + request.getBaseUrl() + " . "; if (LOG.isDebugEnabled()) { errorMessage += ioe; } else { errorMessage += ioe.getMessage(); } break; } } } if (e != null) { LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage, e); } } |
long method | Long method 2 Redundant code3 Feature envy4 Comments to state the obvious 5 Magic numbers 6 Inconsistent naming conventions 7 Inconsistent formatting 8 Poor exception handling 9 Code duplication with slight variations | t | f | t | 0 | 13354 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java/#L4555-L4614 | 2 | 2168 | 13354 | minor | ||
| 2487 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Code complexity 5. Poor naming conventions 6. Inefficient looping 7. Lack of proper commenting or documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Code complexity 5 Poor naming conventions 6 Inefficient looping 7 Lack of proper commenting or documentation | t | f | t | 0 | 14611 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 2487 | 14611 | minor | ||
| 2193 | YES, I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 13477 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2193 | 13477 | major | ||
| 2298 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { reader.setBuffer(buf); if (!reader.beforeMessageRead()) return false; if (!super.readFrom(buf, reader)) return false; switch (reader.state()) { case 3: futId = reader.readLong("futId"); if (!reader.isLastRead()) return false; reader.incrementState(); case 4: locksArr = reader.readObjectArray("locksArr", MessageCollectionItemType.MSG, TxLockList.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 5: nearTxKeysArr = reader.readObjectArray("nearTxKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); case 6: txKeysArr = reader.readObjectArray("txKeysArr", MessageCollectionItemType.MSG, IgniteTxKey.class); if (!reader.isLastRead()) return false; reader.incrementState(); } return reader.afterMessageRead(TxLocksResponse.class); } |
long method | Long method2 Feature envy | t | f | t | 0 | 14025 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/TxLocksResponse.java/#L272-L317 | 2 | 2298 | 14025 | major | ||
| 2466 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected void onRender(Element parent, int index) { super.onRender(parent, index); setLayout(new FitLayout()); setBorders(false); // init components initToolBar(); initGrid(); ContentPanel devicesBundlesPanel = new ContentPanel(); devicesBundlesPanel.setBorders(false); devicesBundlesPanel.setBodyBorder(true); devicesBundlesPanel.setHeaderVisible(false); devicesBundlesPanel.setLayout(new FitLayout()); devicesBundlesPanel.setScrollMode(Scroll.AUTO); devicesBundlesPanel.setTopComponent(toolBar); devicesBundlesPanel.add(grid); add(devicesBundlesPanel); initialized = true; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14563 | https://github.com/eclipse/kapua/blob/11e610c657f7e473b52882833e33a2261bd3d67d/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/client/device/bundles/DeviceTabBundles.java/#L111-L132 | 2 | 2466 | 14563 | minor | ||
| 558 | SequenceFileReader YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Large class 5. Data class 6. Inconsistent levels of abstraction 7. Inappropriate intimacy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private long prevRecordEndOffset; public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord) { this(lastSyncPoint, recordsSinceLastSync, currentRecord, 0, 0 ); } public Offset(long lastSyncPoint, long recordsSinceLastSync, long currentRecord , long currRecordEndOffset, long prevRecordEndOffset) { this.lastSyncPoint = lastSyncPoint; this.recordsSinceLastSync = recordsSinceLastSync; this.currentRecord = currentRecord; this.prevRecordEndOffset = prevRecordEndOffset; this.currRecordEndOffset = currRecordEndOffset; } public Offset(String offset) { try { if(offset==null) { throw new IllegalArgumentException("offset cannot be null"); } if(offset.equalsIgnoreCase("0")) { this.lastSyncPoint = 0; this.recordsSinceLastSync = 0; this.currentRecord = 0; this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } else { String[] parts = offset.split(":"); this.lastSyncPoint = Long.parseLong(parts[0].split("=")[1]); this.recordsSinceLastSync = Long.parseLong(parts[1].split("=")[1]); this.currentRecord = Long.parseLong(parts[2].split("=")[1]); this.prevRecordEndOffset = 0; this.currRecordEndOffset = 0; } } catch (Exception e) { throw new IllegalArgumentException("'" + offset + "' cannot be interpreted. It is not in expected format for SequenceFileReader." + " Format e.g. {sync=123:afterSync=345:record=67}"); } } @Override public String toString() { return '{' + "sync=" + lastSyncPoint + ":afterSync=" + recordsSinceLastSync + ":record=" + currentRecord + ":}"; } @Override public boolean isNextOffset(FileOffset rhs) { if(rhs instanceof Offset) { Offset other = ((Offset) rhs); return other.currentRecord > currentRecord+1; } return false; } @Override public int compareTo(FileOffset o) { Offset rhs = ((Offset) o); if(currentRecord>> 32)); } void increment(boolean syncSeen, long newBytePosition) { if(!syncSeen) { ++recordsSinceLastSync; } else { recordsSinceLastSync = 1; lastSyncPoint = prevRecordEndOffset; } ++currentRecord; prevRecordEndOffset = currRecordEndOffset; currentRecord = newBytePosition; } @Override public Offset clone() { return new Offset(lastSyncPoint, recordsSinceLastSync, currentRecord, currRecordEndOffset, prevRecordEndOffset); } } //class Offset } //class |
data class | Long method2 Feature envy3 Duplicate code4 Large class5 Data class6 Inconsistent levels of abstraction7 Inappropriate intimacy | t | f | t | 0 | 5621 | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-hdfs/src/main/java/com/alibaba/jstorm/hdfs/spout/SequenceFileReader.java/#L104-L212 | 2 | 558 | 5621 | major | ||
| 468 | {"message": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method | t | t | t | 0 | 4551 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 468 | 4551 | major | ||
| 1020 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9347 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 2 | 1020 | 9347 | minor | ||
| 992 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 2 | 992 | 9038 | minor | ||
| 232 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, data class | t | t | t | data class | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 1 | 232 | 2538 | minor | |
| 1223 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Data class" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BasicBundleInfo { private String pkgName; /** * The main dex depends on + the md5 that is currently dependent */ private String unique_tag; private String applicationName; private String version; public Boolean getIsMBundle() { return isMBundle; } public void setIsMBundle(boolean mainBundle) { isMBundle = mainBundle; } private Boolean isMBundle = false; private List dependency = Lists.newArrayList(); private List activities = Lists.newArrayList(); private List services = Lists.newArrayList(); private List receivers = Lists.newArrayList(); private List contentProviders = Lists.newArrayList(); private HashMap remoteFragments= new HashMap(); private HashMap remoteViews = new HashMap(); private HashMap remoteTransactors = new HashMap(); private Boolean isInternal = true; public HashMap getRemoteViews() { return remoteViews; } public void setRemoteViews(HashMap remoteViews) { this.remoteViews = remoteViews; } public HashMap getRemoteTransactors() { return remoteTransactors; } public void setRemoteTransactors(HashMap remoteTransactors) { this.remoteTransactors = remoteTransactors; } public HashMap getRemoteFragments() { return remoteFragments; } public void setRemoteFragments(HashMap remoteFragments) { this.remoteFragments = remoteFragments; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getDependency() { return dependency; } public void setDependency(List dependency) { this.dependency = dependency; } public List getActivities() { return activities; } public void setActivities(List activities) { this.activities = activities; } public List getServices() { return services; } public void setServices(List services) { this.services = services; } public List getReceivers() { return receivers; } public void setReceivers(List receivers) { this.receivers = receivers; } public List getContentProviders() { return contentProviders; } public void setContentProviders(List contentProviders) { this.contentProviders = contentProviders; } public boolean getIsInternal() { return isInternal; } public void setIsInternal(boolean internal) { isInternal = internal; } public String getUnique_tag() { return unique_tag; } public void setUnique_tag(String unique_tag) { this.unique_tag = unique_tag; } } |
data class | 1: data class | t | t | t | 0 | 10340 | https://github.com/alibaba/atlas/blob/e8c7b3f1ff14b2a1df64321c6992b796cae7d732/atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/bundleinfo/model/BasicBundleInfo.java/#L220-L365 | 1 | 1223 | 10340 | critical | ||
| 1276 | { "answer": "YES I found bad smells", "detected_bad_smells": [ "1. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LoopedModelImpl extends MinimalEObjectImpl.Container implements LoopedModel { /** * The cached value of the '{@link #getVisibility() Visibility}' attribute list. * * * @see #getVisibility() * @generated * @ordered */ protected EList visibility; /** * The cached value of the '{@link #getStatic() Static}' attribute list. * * * @see #getStatic() * @generated * @ordered */ protected EList static_; /** * The cached value of the '{@link #getSynchronized() Synchronized}' attribute list. * * * @see #getSynchronized() * @generated * @ordered */ protected EList synchronized_; /** * The cached value of the '{@link #getAbstract() Abstract}' attribute list. * * * @see #getAbstract() * @generated * @ordered */ protected EList abstract_; /** * The cached value of the '{@link #getFinal() Final}' attribute list. * * * @see #getFinal() * @generated * @ordered */ protected EList final_; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * * * @generated */ protected LoopedModelImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return UnorderedGroupsTestPackage.Literals.LOOPED_MODEL; } /** * * * @generated */ public EList getVisibility() { if (visibility == null) { visibility = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY); } return visibility; } /** * * * @generated */ public EList getStatic() { if (static_ == null) { static_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC); } return static_; } /** * * * @generated */ public EList getSynchronized() { if (synchronized_ == null) { synchronized_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED); } return synchronized_; } /** * * * @generated */ public EList getAbstract() { if (abstract_ == null) { abstract_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT); } return abstract_; } /** * * * @generated */ public EList getFinal() { if (final_ == null) { final_ = new EDataTypeEList(String.class, this, UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL); } return final_; } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, UnorderedGroupsTestPackage.LOOPED_MODEL__NAME, oldName, name)); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return getVisibility(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return getStatic(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return getSynchronized(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return getAbstract(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return getFinal(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); getVisibility().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); getStatic().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); getSynchronized().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); getAbstract().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); getFinal().addAll((Collection)newValue); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: getVisibility().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: getStatic().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: getSynchronized().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: getAbstract().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: getFinal().clear(); return; case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case UnorderedGroupsTestPackage.LOOPED_MODEL__VISIBILITY: return visibility != null && !visibility.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__STATIC: return static_ != null && !static_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__SYNCHRONIZED: return synchronized_ != null && !synchronized_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__ABSTRACT: return abstract_ != null && !abstract_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__FINAL: return final_ != null && !final_.isEmpty(); case UnorderedGroupsTestPackage.LOOPED_MODEL__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (visibility: "); result.append(visibility); result.append(", static: "); result.append(static_); result.append(", synchronized: "); result.append(synchronized_); result.append(", abstract: "); result.append(abstract_); result.append(", final: "); result.append(final_); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //LoopedModelImpl |
blob | 1. blob | t | t | t | 0 | 10587 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/unorderedGroupsTest/impl/LoopedModelImpl.java/#L40-L375 | 1 | 1276 | 10587 | minor | ||
| 1172 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_STRING() throws RecognitionException { try { int _type = RULE_STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalXImportSectionTestLang.g:6435:13: ( ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) ) // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) { // InternalXImportSectionTestLang.g:6435:15: ( '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? | '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? ) int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='\"') ) { alt15=1; } else if ( (LA15_0=='\'') ) { alt15=2; } else { NoViableAltException nvae = new NoViableAltException("", 15, 0, input); throw nvae; } switch (alt15) { case 1 : // InternalXImportSectionTestLang.g:6435:16: '\"' ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* ( '\"' )? { match('\"'); // InternalXImportSectionTestLang.g:6435:20: ( '\\\\' . | ~ ( ( '\\\\' | '\"' ) ) )* loop11: do { int alt11=3; int LA11_0 = input.LA(1); if ( (LA11_0=='\\') ) { alt11=1; } else if ( ((LA11_0>='\u0000' && LA11_0<='!')||(LA11_0>='#' && LA11_0<='[')||(LA11_0>=']' && LA11_0<='\uFFFF')) ) { alt11=2; } switch (alt11) { case 1 : // InternalXImportSectionTestLang.g:6435:21: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:28: ~ ( ( '\\\\' | '\"' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop11; } } while (true); // InternalXImportSectionTestLang.g:6435:44: ( '\"' )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0=='\"') ) { alt12=1; } switch (alt12) { case 1 : // InternalXImportSectionTestLang.g:6435:44: '\"' { match('\"'); } break; } } break; case 2 : // InternalXImportSectionTestLang.g:6435:49: '\\'' ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* ( '\\'' )? { match('\''); // InternalXImportSectionTestLang.g:6435:54: ( '\\\\' . | ~ ( ( '\\\\' | '\\'' ) ) )* loop13: do { int alt13=3; int LA13_0 = input.LA(1); if ( (LA13_0=='\\') ) { alt13=1; } else if ( ((LA13_0>='\u0000' && LA13_0<='&')||(LA13_0>='(' && LA13_0<='[')||(LA13_0>=']' && LA13_0<='\uFFFF')) ) { alt13=2; } switch (alt13) { case 1 : // InternalXImportSectionTestLang.g:6435:55: '\\\\' . { match('\\'); matchAny(); } break; case 2 : // InternalXImportSectionTestLang.g:6435:62: ~ ( ( '\\\\' | '\\'' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='&')||(input.LA(1)>='(' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop13; } } while (true); // InternalXImportSectionTestLang.g:6435:79: ( '\\'' )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0=='\'') ) { alt14=1; } switch (alt14) { case 1 : // InternalXImportSectionTestLang.g:6435:79: '\\'' { match('\''); } break; } } break; } } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10197 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase.testlanguages/src-gen/org/eclipse/xtext/xbase/testlanguages/parser/antlr/internal/InternalXImportSectionTestLangLexer.java/#L2127-L2300 | 2 | 1172 | 10197 | critical | |
| 913 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Bug288734TestLanguageSwitch extends Switch { /** * The cached model package * * * @generated */ protected static Bug288734TestLanguagePackage modelPackage; /** * Creates an instance of the switch. * * * @generated */ public Bug288734TestLanguageSwitch() { if (modelPackage == null) { modelPackage = Bug288734TestLanguagePackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * * * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls caseXXX for each class of the model until one returns a non null result; it yields that result. * * * @return the first non-null result returned by a caseXXX call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case Bug288734TestLanguagePackage.MODEL: { Model model = (Model)theEObject; T result = caseModel(model); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TCONSTANT: { TConstant tConstant = (TConstant)theEObject; T result = caseTConstant(tConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TSTRING_CONSTANT: { TStringConstant tStringConstant = (TStringConstant)theEObject; T result = caseTStringConstant(tStringConstant); if (result == null) result = caseTConstant(tStringConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TINTEGER_CONSTANT: { TIntegerConstant tIntegerConstant = (TIntegerConstant)theEObject; T result = caseTIntegerConstant(tIntegerConstant); if (result == null) result = caseTConstant(tIntegerConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TBOOLEAN_CONSTANT: { TBooleanConstant tBooleanConstant = (TBooleanConstant)theEObject; T result = caseTBooleanConstant(tBooleanConstant); if (result == null) result = caseTConstant(tBooleanConstant); if (result == null) result = defaultCase(theEObject); return result; } case Bug288734TestLanguagePackage.TANNOTATION: { TAnnotation tAnnotation = (TAnnotation)theEObject; T result = caseTAnnotation(tAnnotation); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of 'Model'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'Model'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseModel(Model object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TConstant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TConstant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTConstant(TConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TString Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TString Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTStringConstant(TStringConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TInteger Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TInteger Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTIntegerConstant(TIntegerConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TBoolean Constant'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TBoolean Constant'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTBooleanConstant(TBooleanConstant object) { return null; } /** * Returns the result of interpreting the object as an instance of 'TAnnotation'. * * This implementation returns null; * returning a non-null result will terminate the switch. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'TAnnotation'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTAnnotation(TAnnotation object) { return null; } /** * Returns the result of interpreting the object as an instance of 'EObject'. * * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * * @param object the target of the switch. * @return the result of interpreting the object as an instance of 'EObject'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //Bug288734TestLanguageSwitch |
blob | long method, blob | t | t | t | long method | 0 | 8243 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug288734TestLanguage/util/Bug288734TestLanguageSwitch.java/#L26-L238 | 1 | 913 | 8243 | major | |
| 57 | { "output": "YES I found bad smells", "bad_smells": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean hasMatchingKey(Node model1, Node model2) { return keyProvider.getKey(model1).equals(keyProvider.getKey(model2)); } |
feature envy | 1. long method, 2. feature envy | t | t | t | 1. long method | 0 | 987 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/smartTree/NodeStorage.java/#L626-L628 | 1 | 57 | 987 | major | |
| 1614 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void sendMessage(Connection cnx) throws Exception { if (cnx.getServer().getRequiresCredentials()) { // Security is enabled on client as well as on server getMessage().setMessageHasSecurePartFlag(); long userId = -1; if (UserAttributes.userAttributes.get() == null) { // single user mode userId = cnx.getServer().getUserId(); } else { // multi user mode Object id = UserAttributes.userAttributes.get().getServerToId().get(cnx.getServer()); if (id == null) { // This will ensure that this op is retried on another server, unless // the retryCount is exhausted. Fix for Bug 41501 throw new ServerConnectivityException("Connection error while authenticating user"); } userId = (Long) id; } HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { hdos.writeLong(cnx.getConnectionID()); hdos.writeLong(userId); getMessage().setSecurePart(((ConnectionImpl) cnx).encryptBytes(hdos.toByteArray())); } finally { hdos.close(); } } getMessage().send(false); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11471 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/cache/client/internal/AbstractOp.java/#L111-L138 | 2 | 1614 | 11471 | minor | ||
| 1845 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12164 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 1845 | 12164 | major | |
| 2279 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Blob", "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ConfigBoolean extends ConfigVariable { public ConfigBoolean(OptionSpec spec) { super(spec); this.enabled = false; this.isSet = false; } public ConfigBoolean(OptionSpec spec, boolean enabled) { super(spec); this.set(enabled); } private boolean enabled; private boolean isSet; public void set(boolean value) { this.enabled = value; this.isSet = true; } public void set(String value) { this.enabled = parseValue(value); this.isSet = true; } public boolean isSet() { return isSet; } public void addToCommandline(Commandline cmdline) { if (isSet) cmdline.createArgument(true).setValue("-" + spec.getFullName() + "=" + enabled); } private boolean parseValue(String value) { return value.toLowerCase().matches("\\s*(true|yes|on)\\s*"); } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 13785 | https://github.com/apache/royale-compiler/blob/fbd9bc3b9e48c80dbd8c1d32a6f83221e314efdd/royale-ant-tasks/src/main/java/org/apache/royale/compiler/ant/config/ConfigBoolean.java/#L28-L75 | 1 | 2279 | 13785 | major | |
| 839 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Object getValue(final String columnLabel, final Class type) throws SQLException { Object result; if (Object.class == type) { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } else if (boolean.class == type) { result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); } else if (byte.class == type) { result = decrypt(columnLabel, resultSet.getByte(columnLabel)); } else if (short.class == type) { result = decrypt(columnLabel, resultSet.getShort(columnLabel)); } else if (int.class == type) { result = decrypt(columnLabel, resultSet.getInt(columnLabel)); } else if (long.class == type) { result = decrypt(columnLabel, resultSet.getLong(columnLabel)); } else if (float.class == type) { result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); } else if (double.class == type) { result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); } else if (String.class == type) { result = decrypt(columnLabel, resultSet.getString(columnLabel)); } else if (BigDecimal.class == type) { result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); } else if (byte[].class == type) { result = resultSet.getBytes(columnLabel); } else if (Date.class == type) { result = resultSet.getDate(columnLabel); } else if (Time.class == type) { result = resultSet.getTime(columnLabel); } else if (Timestamp.class == type) { result = resultSet.getTimestamp(columnLabel); } else if (URL.class == type) { result = resultSet.getURL(columnLabel); } else if (Blob.class == type) { result = resultSet.getBlob(columnLabel); } else if (Clob.class == type) { result = resultSet.getClob(columnLabel); } else if (SQLXML.class == type) { result = resultSet.getSQLXML(columnLabel); } else if (Reader.class == type) { result = resultSet.getCharacterStream(columnLabel); } else { result = decrypt(columnLabel, resultSet.getObject(columnLabel)); } return result; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 7778 | https://github.com/apache/incubator-shardingsphere/blob/c5cf1d15b02f3a0fb3bda4f15d5f0b3779eac7ba/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java/#L117-L162 | 2 | 839 | 7778 | minor | ||
| 2502 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 14662 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 2502 | 14662 | major | ||
| 754 | Yes, I found bad smells. the bad smells are: 1. Commented out code, 2. Long method, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | Commented out code, 2 Long method, 3 Feature envy, 4 Duplicate code, 5 Magic numbers, 6 Conditional complexity, 7 Inconsistent naming convention, 8 Hard-coded value | t | f | t | . Commented out code, 3. Feature envy, 4. Duplicate code, 5. Magic numbers, 6. Conditional complexity, 7. Inconsistent naming convention, 8. Hard-coded value. | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 2 | 754 | 7039 | minor | |
| 2678 | { "output": "YES I found bad smells", "bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | long method | t | t | t | 0 | 15253 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2678 | 15253 | minor | ||
| 2575 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14915 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 2575 | 14915 | minor | ||
| 1799 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Inappropriate naming/low readability 4. Use of exception handling for control flow 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
feature envy | Long method2 Duplicate code3 Inappropriate naming/low readability4 Use of exception handling for control flow5 Feature envy | t | f | t | 0 | 12009 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 2 | 1799 | 12009 | minor | ||
| 1202 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WSS4JInInterceptorFactory { private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public WSS4JInInterceptor create() { final Map map = new HashMap(); for (Map.Entry entry : properties.entrySet()) { map.put(entry.getKey().toString(), entry.getValue()); } properties.clear(); return new WSS4JInInterceptor(map); } } |
blob | blob, long method | t | t | t | long method | 0 | 10285 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/server/openejb-cxf/src/main/java/org/apache/openejb/server/cxf/config/WSS4JInInterceptorFactory.java/#L28-L48 | 1 | 1202 | 10285 | major | |
| 901 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Builder { private File path; private String interval; private boolean incremental; private File out; private String filter; private boolean ignoreMissingSegments; private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * The two node records to diff specified as a record ID interval. This * parameter is required. * * The interval is specified as two record IDs separated by two full * stops ({@code ..}). In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345..46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * Instead of using a full record ID, it is possible to use the special * placeholder {@code head}. This placeholder is translated to the * record ID of the most recent head state. * * @param interval an interval between two node record IDs. * @return this builder. */ public Builder withInterval(String interval) { this.interval = checkNotNull(interval); return this; } /** * Set whether or not to perform an incremental diff of the specified * interval. An incremental diff shows every change between the two * records at every revision available to the segment store. This * parameter is not mandatory and defaults to {@code false}. * * @param incremental {@code true} to perform an incremental diff, * {@code false} otherwise. * @return this builder. */ public Builder withIncremental(boolean incremental) { this.incremental = incremental; return this; } /** * The file where the output of this command is stored. this parameter * is mandatory. * * @param file the output file. * @return this builder. */ public Builder withOutput(File file) { this.out = checkNotNull(file); return this; } /** * The path to a subtree. If specified, this parameter allows to * restrict the diff to the specified subtree. This parameter is not * mandatory and defaults to the entire tree. * * @param filter a path used as as filter for the resulting diff. * @return this builder. */ public Builder withFilter(String filter) { this.filter = checkNotNull(filter); return this; } /** * Whether to ignore exceptions caused by missing segments in the * segment store. This parameter is not mandatory and defaults to {@code * false}. * * @param ignoreMissingSegments {@code true} to ignore exceptions caused * by missing segments, {@code false} * otherwise. * @return this builder. */ public Builder withIgnoreMissingSegments(boolean ignoreMissingSegments) { this.ignoreMissingSegments = ignoreMissingSegments; return this; } /** * Create an executable version of the {@link Diff} command. * * @return an instance of {@link Runnable}. */ public Diff build() { checkNotNull(path); checkNotNull(interval); checkNotNull(out); checkNotNull(filter); return new Diff(this); } } |
data class | data class, long method | t | t | t | long method | 0 | 8158 | https://github.com/apache/jackrabbit-oak/blob/fa85f54a065e01c0a1cb8c03af74194fdf521ddd/oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/Diff.java/#L56-L171 | 1 | 901 | 8158 | minor | |
| 1228 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10354 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 1228 | 10354 | minor | ||
| 2541 | YES, I found bad smells the bad smells are: Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected GraphicsNode createImageGraphicsNode( BridgeContext ctx, Element imageElement, ParsedURL purl) { AbstractFOPBridgeContext bridgeCtx = (AbstractFOPBridgeContext)ctx; ImageManager manager = bridgeCtx.getImageManager(); ImageSessionContext sessionContext = bridgeCtx.getImageSessionContext(); try { ImageInfo info = manager.getImageInfo(purl.toString(), sessionContext); ImageFlavor[] supportedFlavors = getSupportedFlavours(); Image image = manager.getImage(info, supportedFlavors, sessionContext); //TODO color profile overrides aren't handled, yet! //ICCColorSpaceExt colorspaceOverride = extractColorSpace(e, ctx); AbstractGraphicsNode specializedNode = null; if (image instanceof ImageXMLDOM) { ImageXMLDOM xmlImage = (ImageXMLDOM)image; if (xmlImage.getDocument() instanceof SVGDocument) { //Clone DOM because the Batik's CSS Parser attaches to the DOM and is therefore //not thread-safe. SVGDocument clonedDoc = (SVGDocument)BatikUtil.cloneSVGDocument( xmlImage.getDocument()); return createSVGImageNode(ctx, imageElement, clonedDoc); } else { //Convert image to Graphics2D image = manager.convertImage(xmlImage, new ImageFlavor[] {ImageFlavor.GRAPHICS2D}); } } if (image instanceof ImageRawJPEG) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageRawCCITTFax) { specializedNode = createLoaderImageNode(image, ctx, imageElement, purl); } else if (image instanceof ImageGraphics2D) { ImageGraphics2D g2dImage = (ImageGraphics2D)image; specializedNode = new Graphics2DNode(g2dImage); } else { ctx.getUserAgent().displayError( new ImageException("Cannot convert an image to a usable format: " + purl)); } if (specializedNode != null) { Rectangle2D imgBounds = getImageBounds(ctx, imageElement); Rectangle2D bounds = specializedNode.getPrimitiveBounds(); float [] vb = new float[4]; vb[0] = 0; // x vb[1] = 0; // y vb[2] = (float) bounds.getWidth(); // width vb[3] = (float) bounds.getHeight(); // height // handles the 'preserveAspectRatio', 'overflow' and 'clip' // and sets the appropriate AffineTransform to the image node initializeViewport(ctx, imageElement, specializedNode, vb, imgBounds); return specializedNode; } } catch (Exception e) { ctx.getUserAgent().displayError(e); } //Fallback return superCreateGraphicsNode(ctx, imageElement, purl); } |
feature envy | Feature envy | t | f | t | 0 | 14775 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java/#L70-L131 | 2 | 2541 | 14775 | minor | ||
| 621 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class UpdateEntityResponse extends UpdateResponse { private final V _entity; public UpdateEntityResponse(final HttpStatus status, final V entity) { super(status); _entity = entity; } public boolean hasEntity() { return _entity != null; } public V getEntity() { return _entity; } } |
data class | 1. data class | t | t | t | 0 | 6238 | https://github.com/linkedin/rest.li/blob/ad74aa98da8a55ad9c339d0769a3e8fb495765af/restli-server/src/main/java/com/linkedin/restli/server/UpdateEntityResponse.java/#L31-L50 | 1 | 621 | 6238 | major | ||
| 2841 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @VisibleForTesting @Nonnull static Supplier supplierFromDimensionSelector(final DimensionSelector selector) { Preconditions.checkNotNull(selector, "selector"); return () -> { final IndexedInts row = selector.getRow(); if (row.size() == 1) { return selector.lookupName(row.get(0)); } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return null; } }; } |
long method | long method | t | t | t | 0 | 1663 | https://github.com/apache/incubator-druid/blob/8ca7cb4886dcaeeaaea3a06aceb9e6d50eeecab5/processing/src/main/java/org/apache/druid/segment/virtual/ExpressionSelectors.java/#L311-L327 | 1 | 2841 | 1663 | minor | ||
| 1199 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HandleConfigDriveIsoCommand extends Command { @LogLevel(LogLevel.Log4jLevel.Off) private String isoData; private String isoFile; private boolean create = false; private DataStoreTO destStore; public HandleConfigDriveIsoCommand(String isoFile, String isoData, DataStoreTO destStore, boolean create) { this.isoFile = isoFile; this.isoData = isoData; this.destStore = destStore; this.create = create; } @Override public boolean executeInSequence() { return false; } public String getIsoData() { return isoData; } public boolean isCreate() { return create; } public DataStoreTO getDestStore() { return destStore; } public String getIsoFile() { return isoFile; } } |
data class | data class | t | t | t | 0 | 10278 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/core/src/main/java/com/cloud/agent/api/HandleConfigDriveIsoCommand.java/#L24-L60 | 1 | 1199 | 10278 | major | ||
| 1899 | {"message": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | 1. long method | t | t | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 1 | 1899 | 12355 | minor | ||
| 2130 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static byte[] getIP() { try { Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; byte[] internalIP = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { byte[] ipByte = ip.getAddress(); if (ipByte.length == 4) { if (ipCheck(ipByte)) { if (!isInternalIP(ipByte)) { return ipByte; } else if (internalIP == null) { internalIP = ipByte; } } } } } } if (internalIP != null) { return internalIP; } else { throw new RuntimeException("Can not get local ip"); } } catch (Exception e) { throw new RuntimeException("Can not get local ip", e); } } |
long method | long method, blob | t | t | t | blob | 0 | 13230 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/common/src/main/java/org/apache/rocketmq/common/UtilAll.java/#L484-L516 | 1 | 2130 | 13230 | major | |
| 1892 | {"response": "YES, I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 12318 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 1892 | 12318 | major | ||
| 2096 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean doAction( ) throws Exception { if ( Policy.TRACING_ACTIONS ) { System.out.println( "Edit data source action >> Runs ..." ); //$NON-NLS-1$ } DataSourceHandle handle = (DataSourceHandle) getSelection( ); DataSourceEditor dialog = new AdvancedDataSourceEditor( PlatformUI .getWorkbench( ).getDisplay( ).getActiveShell( ), handle ); return ( dialog.open( ) == IDialogConstants.OK_ID ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 13148 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/actions/EditDataSourceAction.java/#L59-L70 | 2 | 2096 | 13148 | minor | ||
| 1623 | { "message": "YES I found bad smells", "bad_smells": [ "1. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextResourceLink other = (ContextResourceLink) obj; if (factory == null) { if (other.factory != null) { return false; } } else if (!factory.equals(other.factory)) { return false; } if (global == null) { if (other.global != null) { return false; } } else if (!global.equals(other.global)) { return false; } return true; } |
long method | 1 Long Method | t | f | t | 0 | 11490 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/ContextResourceLink.java/#L94-L121 | 1 | 1623 | 11490 | minor | ||
| 5084 | {"message":"YES I found bad smells","detected_bad_smells":["Blob","Data Class","Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProviderCreditReversalDetails", propOrder = { "amazonProviderCreditReversalId", "sellerId", "providerSellerId", "creditReversalReferenceId", "creditReversalAmount", "creationTimestamp", "creditReversalStatus", "creditReversalNote" }) public class ProviderCreditReversalDetails { @XmlElement(name = "AmazonProviderCreditReversalId", required = true) protected String amazonProviderCreditReversalId; @XmlElement(name = "SellerId", required = true) protected String sellerId; @XmlElement(name = "ProviderSellerId", required = true) protected String providerSellerId; @XmlElement(name = "CreditReversalReferenceId", required = true) protected String creditReversalReferenceId; @XmlElement(name = "CreditReversalAmount", required = true) protected Price creditReversalAmount; @XmlElement(name = "CreationTimestamp", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar creationTimestamp; @XmlElement(name = "CreditReversalStatus", required = true) protected Status creditReversalStatus; @XmlElement(name = "CreditReversalNote") protected String creditReversalNote; public ProviderCreditReversalDetails() { super(); } /** * Returns the amazonProviderCreditReversalId from notification * * @return Returns the amazonProviderCreditReversalId from notification */ public String getAmazonProviderCreditReversalId() { return amazonProviderCreditReversalId; } /** * Returns the sellerId from notification * * @return Returns the sellerId from notification */ public String getSellerId() { return sellerId; } /** * Returns the providerSellerId from notification * * @return Returns the providerSellerId from notification */ public String getProviderSellerId() { return providerSellerId; } /** * Returns the creditReversalReferenceId from notification * * @return Returns the creditReversalReferenceId from notification */ public String getCreditReversalReferenceId() { return creditReversalReferenceId; } /** * Returns the creditReversalAmount from notification * * @return Returns the creditReversalAmount from notification */ public Price getCreditReversalAmount() { return creditReversalAmount; } /** * Returns the creationTimestamp from notification * * @return Returns the creationTimestamp from notification */ public XMLGregorianCalendar getCreationTimestamp() { return creationTimestamp; } /** * Returns the creditReversalStatus from notification * * @return Returns the creditReversalStatus from notification */ public Status getCreditReversalStatus() { return creditReversalStatus; } /** * Returns the creditReversalNote from notification * * @return Returns the creditReversalNote from notification */ public String getCreditReversalNote() { return creditReversalNote; } /** * String representation of providerCreditReversalNotification */ @Override public String toString() { return "ProviderCreditReversalDetails{" + "amazonProviderCreditReversalId=" + amazonProviderCreditReversalId + ", sellerId=" + sellerId + ", providerId=" + providerSellerId + ", creditReversalReferenceId=" + creditReversalReferenceId + ", creditReversalAmount=" + creditReversalAmount + ", creationTimestamp=" + creationTimestamp + ", creditReversalStatus=" + creditReversalStatus + ", creditReversalNote=" + creditReversalNote + '}'; } } |
data class | blob, data class, long method | t | t | t | blob, long method | 0 | 14204 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/response/ipn/model/ProviderCreditReversalDetails.java/#L25-L145 | 1 | 5084 | 14204 | major | |
| 2696 | {"response": "YES I found bad smells", "bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
long method | long method, data class | t | t | t | data class | 0 | 15319 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 1 | 2696 | 15319 | minor | |
| 369 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 3819 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 1 | 369 | 3819 | major | |
| 250 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static final class VertexGroupItem extends Tuple4, Long> { private final Either.Right nullValue = new Either.Right<>(NullValue.getInstance()); public VertexGroupItem() { reset(); } public K getVertexId() { return f0; } public void setVertexId(K vertexId) { f0 = vertexId; } public K getGroupRepresentativeId() { return f1; } public void setGroupRepresentativeId(K groupRepresentativeId) { f1 = groupRepresentativeId; } public VGV getVertexGroupValue() { return f2.isLeft() ? f2.left() : null; } public void setVertexGroupValue(VGV vertexGroupValue) { if (vertexGroupValue == null) { f2 = nullValue; } else { f2 = new Either.Left<>(vertexGroupValue); } } public Long getVertexGroupCount() { return f3; } public void setVertexGroupCount(Long vertexGroupCount) { f3 = vertexGroupCount; } /** * Resets the fields to initial values. This is necessary if the tuples are reused and not all fields were modified. */ public void reset() { f0 = null; f1 = null; f2 = nullValue; f3 = 0L; } } |
data class | long method, data class | t | t | t | long method | 0 | 2685 | https://github.com/apache/flink/blob/8068c8775ad067d75828e6360e7e0994348da9b9/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/Summarization.java/#L214-L268 | 1 | 250 | 2685 | major | |
| 394 | YES, I found bad smells. the bad smells are: 1. Long method, 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final EObject entryRuleXMultiplicativeExpression() throws RecognitionException { EObject current = null; EObject iv_ruleXMultiplicativeExpression = null; try { // InternalEntities.g:1696:66: (iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF ) // InternalEntities.g:1697:2: iv_ruleXMultiplicativeExpression= ruleXMultiplicativeExpression EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXMultiplicativeExpressionRule()); } pushFollow(FOLLOW_1); iv_ruleXMultiplicativeExpression=ruleXMultiplicativeExpression(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXMultiplicativeExpression; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } |
long method | Long method,2 Feature envy,3 Redundant code,4 Complicated control flow,5 Code duplication,6 Poor exception handling | t | f | t | 2. Feature envy, 3. Redundant code, 4. Complicated control flow, 5. Code duplication, 6. Poor exception handling. | 0 | 3978 | https://github.com/eclipse/xtext-web/blob/ff7aa71dbdf9f1abf4cf3e3911c17707293dfe49/org.eclipse.xtext.web.example.entities/src-gen/org/eclipse/xtext/web/example/entities/parser/antlr/internal/InternalEntitiesParser.java/#L5034-L5068 | 2 | 394 | 3978 | minor | |
| 2071 | YES I found bad smells the bad smells are: 1)Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (e.g. hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | )Long method 2)Feature envy 3)Repeated code 4)Naming inconsistencies (eg hashKeyValue vs hashKeyName) 5)Multiple responsibilities (method is handling both DynamoDB operations and transferring flowFiles) 6)Catching generic exceptions instead of specific ones 7)Poor code organization (order of variable declarations and logic is not clear) | t | f | t | 0 | 13025 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2071 | 13025 | major | ||
| 382 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Public @InterfaceStability.Evolving public class Cluster { @InterfaceStability.Evolving public static enum JobTrackerStatus {INITIALIZING, RUNNING}; private ClientProtocolProvider clientProtocolProvider; private ClientProtocol client; private UserGroupInformation ugi; private Configuration conf; private FileSystem fs = null; private Path sysDir = null; private Path stagingAreaDir = null; private Path jobHistoryDir = null; private static final Log LOG = LogFactory.getLog(Cluster.class); private static ServiceLoader frameworkLoader = ServiceLoader.load(ClientProtocolProvider.class); static { ConfigUtil.loadResources(); } public Cluster(Configuration conf) throws IOException { this(null, conf); } public Cluster(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { this.conf = conf; this.ugi = UserGroupInformation.getCurrentUser(); initialize(jobTrackAddr, conf); } private void initialize(InetSocketAddress jobTrackAddr, Configuration conf) throws IOException { synchronized (frameworkLoader) { for (ClientProtocolProvider provider : frameworkLoader) { LOG.debug("Trying ClientProtocolProvider : " + provider.getClass().getName()); ClientProtocol clientProtocol = null; try { if (jobTrackAddr == null) { clientProtocol = provider.create(conf); } else { clientProtocol = provider.create(jobTrackAddr, conf); } if (clientProtocol != null) { clientProtocolProvider = provider; client = clientProtocol; LOG.debug("Picked " + provider.getClass().getName() + " as the ClientProtocolProvider"); break; } else { LOG.debug("Cannot pick " + provider.getClass().getName() + " as the ClientProtocolProvider - returned null protocol"); } } catch (Exception e) { LOG.info("Failed to use " + provider.getClass().getName() + " due to error: " + e.getMessage()); } } } if (null == clientProtocolProvider || null == client) { throw new IOException( "Cannot initialize Cluster. Please check your configuration for " + MRConfig.FRAMEWORK_NAME + " and the correspond server addresses."); } } ClientProtocol getClient() { return client; } Configuration getConf() { return conf; } /** * Close the Cluster. */ public synchronized void close() throws IOException { clientProtocolProvider.close(client); } private Job[] getJobs(JobStatus[] stats) throws IOException { List jobs = new ArrayList(); for (JobStatus stat : stats) { jobs.add(Job.getInstance(this, stat, new JobConf(stat.getJobFile()))); } return jobs.toArray(new Job[0]); } /** * Get the file system where job-specific files are stored * * @return object of FileSystem * @throws IOException * @throws InterruptedException */ public synchronized FileSystem getFileSystem() throws IOException, InterruptedException { if (this.fs == null) { try { this.fs = ugi.doAs(new PrivilegedExceptionAction() { public FileSystem run() throws IOException, InterruptedException { final Path sysDir = new Path(client.getSystemDir()); return sysDir.getFileSystem(getConf()); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } } return fs; } /** * Get job corresponding to jobid. * * @param jobId * @return object of {@link Job} * @throws IOException * @throws InterruptedException */ public Job getJob(JobID jobId) throws IOException, InterruptedException { JobStatus status = client.getJobStatus(jobId); if (status != null) { JobConf conf; try { conf = new JobConf(status.getJobFile()); } catch (RuntimeException ex) { // If job file doesn't exist it means we can't find the job if (ex.getCause() instanceof FileNotFoundException) { return null; } else { throw ex; } } return Job.getInstance(this, status, conf); } return null; } /** * Get all the queues in cluster. * * @return array of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo[] getQueues() throws IOException, InterruptedException { return client.getQueues(); } /** * Get queue information for the specified name. * * @param name queuename * @return object of {@link QueueInfo} * @throws IOException * @throws InterruptedException */ public QueueInfo getQueue(String name) throws IOException, InterruptedException { return client.getQueue(name); } /** * Get log parameters for the specified jobID or taskAttemptID * @param jobID the job id. * @param taskAttemptID the task attempt id. Optional. * @return the LogParams * @throws IOException * @throws InterruptedException */ public LogParams getLogParams(JobID jobID, TaskAttemptID taskAttemptID) throws IOException, InterruptedException { return client.getLogFileParams(jobID, taskAttemptID); } /** * Get current cluster status. * * @return object of {@link ClusterMetrics} * @throws IOException * @throws InterruptedException */ public ClusterMetrics getClusterStatus() throws IOException, InterruptedException { return client.getClusterMetrics(); } /** * Get all active trackers in the cluster. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getActiveTaskTrackers() throws IOException, InterruptedException { return client.getActiveTrackers(); } /** * Get blacklisted trackers. * * @return array of {@link TaskTrackerInfo} * @throws IOException * @throws InterruptedException */ public TaskTrackerInfo[] getBlackListedTaskTrackers() throws IOException, InterruptedException { return client.getBlacklistedTrackers(); } /** * Get all the jobs in cluster. * * @return array of {@link Job} * @throws IOException * @throws InterruptedException * @deprecated Use {@link #getAllJobStatuses()} instead. */ @Deprecated public Job[] getAllJobs() throws IOException, InterruptedException { return getJobs(client.getAllJobs()); } /** * Get job status for all jobs in the cluster. * @return job status for all jobs in cluster * @throws IOException * @throws InterruptedException */ public JobStatus[] getAllJobStatuses() throws IOException, InterruptedException { return client.getAllJobs(); } /** * Grab the jobtracker system directory path where * job-specific files will be placed. * * @return the system directory where job-specific files are to be placed. */ public Path getSystemDir() throws IOException, InterruptedException { if (sysDir == null) { sysDir = new Path(client.getSystemDir()); } return sysDir; } /** * Grab the jobtracker's view of the staging directory path where * job-specific files will be placed. * * @return the staging directory where job-specific files are to be placed. */ public Path getStagingAreaDir() throws IOException, InterruptedException { if (stagingAreaDir == null) { stagingAreaDir = new Path(client.getStagingAreaDir()); } return stagingAreaDir; } /** * Get the job history file path for a given job id. The job history file at * this path may or may not be existing depending on the job completion state. * The file is present only for the completed jobs. * @param jobId the JobID of the job submitted by the current user. * @return the file path of the job history file * @throws IOException * @throws InterruptedException */ public String getJobHistoryUrl(JobID jobId) throws IOException, InterruptedException { if (jobHistoryDir == null) { jobHistoryDir = new Path(client.getJobHistoryDir()); } return new Path(jobHistoryDir, jobId.toString() + "_" + ugi.getShortUserName()).toString(); } /** * Gets the Queue ACLs for current user * @return array of QueueAclsInfo object for current user. * @throws IOException */ public QueueAclsInfo[] getQueueAclsForCurrentUser() throws IOException, InterruptedException { return client.getQueueAclsForCurrentUser(); } /** * Gets the root level queues. * @return array of JobQueueInfo object. * @throws IOException */ public QueueInfo[] getRootQueues() throws IOException, InterruptedException { return client.getRootQueues(); } /** * Returns immediate children of queueName. * @param queueName * @return array of JobQueueInfo which are children of queueName * @throws IOException */ public QueueInfo[] getChildQueues(String queueName) throws IOException, InterruptedException { return client.getChildQueues(queueName); } /** * Get the JobTracker's status. * * @return {@link JobTrackerStatus} of the JobTracker * @throws IOException * @throws InterruptedException */ public JobTrackerStatus getJobTrackerStatus() throws IOException, InterruptedException { return client.getJobTrackerStatus(); } /** * Get the tasktracker expiry interval for the cluster * @return the expiry interval in msec */ public long getTaskTrackerExpiryInterval() throws IOException, InterruptedException { return client.getTaskTrackerExpiryInterval(); } /** * Get a delegation token for the user from the JobTracker. * @param renewer the user who can renew the token * @return the new token * @throws IOException */ public Token getDelegationToken(Text renewer) throws IOException, InterruptedException{ // client has already set the service return client.getDelegationToken(renewer); } /** * Renew a delegation token * @param token the token to renew * @return the new expiration time * @throws InvalidToken * @throws IOException * @deprecated Use {@link Token#renew} instead */ public long renewDelegationToken(Token token ) throws InvalidToken, IOException, InterruptedException { return token.renew(getConf()); } /** * Cancel a delegation token from the JobTracker * @param token the token to cancel * @throws IOException * @deprecated Use {@link Token#cancel} instead */ public void cancelDelegationToken(Token token ) throws IOException, InterruptedException { token.cancel(getConf()); } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 3913 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java/#L50-L429 | 1 | 382 | 3913 | major |
| 1587 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | long method, data class | t | t | t | data class | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 1 | 1587 | 11373 | minor | |
| 5570 | {"message": "YES I found bad smells. The bad smells are: 1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configureInputJobProperties(TableDesc tableDesc, Map jobProperties) { try { Map tableProperties = tableDesc.getJobProperties(); String jobInfoProperty = tableProperties.get(HCatConstants.HCAT_KEY_JOB_INFO); if (jobInfoProperty != null) { LinkedList inputJobInfos = (LinkedList) HCatUtil.deserialize( jobInfoProperty); if (inputJobInfos == null || inputJobInfos.isEmpty()) { throw new IOException("No InputJobInfo was set in job config"); } InputJobInfo inputJobInfo = inputJobInfos.getLast(); HCatTableInfo tableInfo = inputJobInfo.getTableInfo(); HCatSchema dataColumns = tableInfo.getDataColumns(); List dataFields = dataColumns.getFields(); StringBuilder columnNamesSb = new StringBuilder(); StringBuilder typeNamesSb = new StringBuilder(); for (HCatFieldSchema dataField : dataFields) { if (columnNamesSb.length() > 0) { columnNamesSb.append(","); typeNamesSb.append(":"); } columnNamesSb.append(dataField.getName()); typeNamesSb.append(dataField.getTypeString()); } jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS, columnNamesSb.toString()); jobProperties.put(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, typeNamesSb.toString()); boolean isTransactionalTable = AcidUtils.isTablePropertyTransactional(tableProperties); AcidUtils.AcidOperationalProperties acidOperationalProperties = AcidUtils.getAcidOperationalProperties(tableProperties); AcidUtils.setAcidOperationalProperties( jobProperties, isTransactionalTable, acidOperationalProperties); } } catch (IOException e) { throw new IllegalStateException("Failed to set output path", e); } } |
long method | 1. long method | t | t | f | long method | 0 | 8187 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/hcatalog/core/src/main/java/org/apache/hive/hcatalog/mapreduce/FosterStorageHandler.java/#L107-L150 | 2 | 5570 | 8187 | minor | |
| 654 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
feature envy | Long method, 2Feature envy | t | f | t | .Long method | 0 | 6390 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 654 | 6390 | major | |
| 1338 | YES I found bad smells The bad smells are: 1. Magic numbers 2. Long method 3. Complex logic 4. Feature envy 5. Poor variable naming 6. Repeated code 7. Inconsistent formatting 8. Inefficient use of memory 9. Use of ternary operator 10. Poor exception handling | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Magic numbers2 Long method3 Complex logic4 Feature envy5 Poor variable naming6 Repeated code7 Inconsistent formatting8 Inefficient use of memory9 Use of ternary operator | t | f | t | 0 | 10733 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 1338 | 10733 | major | ||
| 1390 | YES I found bad smells the bad smells are: 1.Long method, 2.Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void close() throws IOException { boolean success = false; try { if (meta != null) { meta.writeInt(-1); // write EOF marker CodecUtil.writeFooter(meta); // write checksum } if (data != null) { CodecUtil.writeFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.close(data, meta); } else { IOUtils.closeWhileHandlingException(data, meta); } meta = data = null; } } |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 10841 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene70/Lucene70DocValuesConsumer.java/#L83-L103 | 2 | 1390 | 10841 | minor | |
| 398 | {"message": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class GitHubUser implements Serializable { private final long id; private final String url; private final String login; private final String avatarUrl; private final String gravatarId; private String name; private String email; public GitHubUser(long id, String url, String login, String avatarUrl, String gravatarId) { this.id = id; this.url = url; this.login = login; this.avatarUrl = avatarUrl; this.gravatarId = gravatarId; } public Long getId() { return id; } public String getUrl() { return url; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getGravatarId() { return gravatarId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
data class | data class | t | t | t | 0 | 4066 | https://github.com/spring-projects/spring-social-github/blob/7939988245be49486d27c42c30bfb0a567c6ec1b/spring-social-github/src/main/java/org/springframework/social/github/api/GitHubUser.java/#L30-L72 | 1 | 398 | 4066 | critical | ||
| 900 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex code 5. Multiple method calls within loops 6. Overly complex conditional statements 7. Multiple try-catch blocks with similar structure 8. Unclear variable names 9. Code repetition 10. Inconsistent formatting 11. Comments that do not add value to the code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void refreshInternal(Collection objs, OpCallbacks call) { if (objs == null || objs.isEmpty()) return; List exceps = null; try { // collect instances that need a refresh Collection load = null; StateManagerImpl sm; Object obj; for (Iterator itr = objs.iterator(); itr.hasNext();) { obj = itr.next(); if (obj == null) continue; try { sm = getStateManagerImpl(obj, true); if ((processArgument(OpCallbacks.OP_REFRESH, obj, sm, call) & OpCallbacks.ACT_RUN) == 0) continue; if (sm != null) { if (sm.isDetached()) throw newDetachedException(obj, "refresh"); else if (sm.beforeRefresh(true)) { if (load == null) load = new ArrayList<>(objs.size()); load.add(sm); } int level = _fc.getReadLockLevel(); int timeout = _fc.getLockTimeout(); _lm.refreshLock(sm, level, timeout, null); sm.readLocked(level, level); } else if (assertPersistenceCapable(obj).pcIsDetached() == Boolean.TRUE) throw newDetachedException(obj, "refresh"); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } // refresh all if (load != null) { Collection failed = _store.loadAll(load, null, StoreManager.FORCE_LOAD_REFRESH, _fc, null); if (failed != null && !failed.isEmpty()) exceps = add(exceps, newObjectNotFoundException(failed)); // perform post-refresh transitions and make sure all fetch // group fields are loaded for (Iterator itr = load.iterator(); itr.hasNext();) { sm = (StateManagerImpl) itr.next(); if (failed != null && failed.contains(sm.getId())) continue; try { sm.afterRefresh(); sm.load(_fc, StateManagerImpl.LOAD_FGS, null, null, false); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } // now invoke postRefresh on all the instances for (Iterator itr = objs.iterator(); itr.hasNext();) { try { sm = getStateManagerImpl(itr.next(), true); if (sm != null && !sm.isDetached()) fireLifecycleEvent(sm.getManagedInstance(), null, sm.getMetaData(), LifecycleEvent.AFTER_REFRESH); } catch (OpenJPAException ke) { exceps = add(exceps, ke); } } } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } throwNestedExceptions(exceps, false); } |
long method | Long method2 Feature envy3 Duplicate code4 Complex code5 Multiple method calls within loops6 Overly complex conditional statements7 Multiple try-catch blocks with similar structure8 Unclear variable names9 Code repetition | t | f | t | 0 | 8153 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java/#L3172-L3253 | 2 | 900 | 8153 | major | ||
| 2750 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Blob" }, { "2": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String getLoggerLevel(String loggerName) { String result = null; /*[IF Sidecar19-SE]*/ try { Object logger = getLoggerFromName(loggerName); /*[ELSE] Logger logger = LogManager.getLogManager().getLogger(loggerName); /*[ENDIF]*/ if (logger != null) { // The named Logger exists. Now attempt to obtain its log level. /*[IF Sidecar19-SE]*/ Object level = logger_getLevel.invoke(logger); /*[ELSE] Level level = logger.getLevel(); /*[ENDIF]*/ if (level != null) { /*[IF Sidecar19-SE]*/ result = (String)level_getName.invoke(level); /*[ELSE] result = level.getName(); /*[ENDIF]*/ } else { // A null return from getLevel() means that the Logger // is inheriting its log level from an ancestor. Return an // empty string to the caller. result = ""; //$NON-NLS-1$ } } /*[IF Sidecar19-SE]*/ } catch (Exception e) { throw handleError(e); } /*[ENDIF]*/ return result; } |
long method | 1: blob, 2: long method | t | t | t | 1: blob | 0 | 818 | https://github.com/eclipse/openj9/blob/4911084853eb75b20e037c434ad4521b7317ebfb/jcl/src/java.management/share/classes/com/ibm/java/lang/management/internal/LoggingMXBeanImpl.java/#L148-L186 | 1 | 2750 | 818 | minor | |
| 216 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 2343 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 216 | 2343 | major | ||
| 1893 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Action getBinaryBitwiseExpressionLhsAction_1_0_0_0() { return cBinaryBitwiseExpressionLhsAction_1_0_0_0; } //op=BitwiseOROperator public Assignment getOpAssignment_1_0_0_1() { return cOpAssignment_1_0_0_1; } //BitwiseOROperator public RuleCall getOpBitwiseOROperatorParserRuleCall_1_0_0_1_0() { return cOpBitwiseOROperatorParserRuleCall_1_0_0_1_0; } //rhs=BitwiseXORExpression public Assignment getRhsAssignment_1_1() { return cRhsAssignment_1_1; } //BitwiseXORExpression public RuleCall getRhsBitwiseXORExpressionParserRuleCall_1_1_0() { return cRhsBitwiseXORExpressionParserRuleCall_1_1_0; } } public class BitwiseOROperatorElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.BitwiseOROperator"); private final Keyword cVerticalLineKeyword = (Keyword)rule.eContents().get(1); //BitwiseOROperator BinaryBitwiseOperator: // '|'; @Override public ParserRule getRule() { return rule; } //'|' public Keyword getVerticalLineKeyword() { return cVerticalLineKeyword; } } public class LogicalANDExpressionElements extends AbstractParserRuleElementFinder { private final ParserRule rule = (ParserRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.N4JS.LogicalANDExpression"); private final Group cGroup = (Group)rule.eContents().get(1); private final RuleCall cBitwiseORExpressionParserRuleCall_0 = (RuleCall)cGroup.eContents().get(0); private final Group cGroup_1 = (Group)cGroup.eContents().get(1); private final Group cGroup_1_0 = (Group)cGroup_1.eContents().get(0); private final Group cGroup_1_0_0 = (Group)cGroup_1_0.eContents().get(0); private final Action cBinaryLogicalExpressionLhsAction_1_0_0_0 = (Action)cGroup_1_0_0.eContents().get(0); private final Assignment cOpAssignment_1_0_0_1 = (Assignment)cGroup_1_0_0.eContents().get(1); private final RuleCall cOpLogicalANDOperatorParserRuleCall_1_0_0_1_0 = (RuleCall)cOpAssignment_1_0_0_1.eContents().get(0); private final Assignment cRhsAssignment_1_1 = (Assignment)cGroup_1.eContents().get(1); private final RuleCall cRhsBitwiseORExpressionParserRuleCall_1_1_0 = (RuleCall)cRhsAssignment_1_1.eContents().get(0); //// $ (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) // rhs=BitwiseORExpression)*; @Override public ParserRule getRule() { return rule; } //BitwiseORExpression (=> ({BinaryLogicalExpression.lhs=current} op=LogicalANDOperator) //rhs=BitwiseORExpression)* public Group getGroup() { return cGroup; } //BitwiseORExpression public RuleCall getBitwiseORExpressionParserRuleCall_0() { return cBitwiseORExpressionParserRuleCall_0; } |
data class | long method, data class | t | t | t | long method | 0 | 12320 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js/src-gen/org/eclipse/n4js/services/N4JSGrammarAccess.java/#L6096-L6144 | 1 | 1893 | 12320 | minor | |
| 643 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected SQLBuffer toBulkOperation(ClassMapping mapping, Select sel, JDBCStore store, Object[] params, Map updateParams) { SQLBuffer sql = new SQLBuffer(this); if (updateParams == null) { if (requiresTargetForDelete) { sql.append("DELETE "); SQLBuffer deleteTargets = getDeleteTargets(sel); sql.append(deleteTargets); sql.append(" FROM "); } else { sql.append("DELETE FROM "); } } else sql.append("UPDATE "); sel.addJoinClassConditions(); // if there is only a single table in the select, then we can // just issue a single DELETE FROM TABLE WHERE // statement; otherwise, since SQL doesn't allow deleting // from one of a multi-table select, we need to issue a subselect // like DELETE FROM TABLE WHERE EXISTS // (SELECT 1 FROM TABLE t0 WHERE t0.ID = TABLE.ID); also, some // databases do not allow aliases in delete statements, which // also causes us to use a subselect Collection selectedTables = getSelectTableAliases(sel); if (selectedTables.size() == 1 && supportsSubselect && allowsAliasInBulkClause) { SQLBuffer from; if (sel.getFromSelect() != null) from = getFromSelect(sel, false); else from = getFrom(sel, false); sql.append(from); appendUpdates(sel, store, sql, params, updateParams, allowsAliasInBulkClause); SQLBuffer where = sel.getWhere(); if (where != null && !where.isEmpty()) { sql.append(" WHERE "); sql.append(where); } return sql; } Table table = mapping.getTable(); String tableName = getFullName(table, false); // only use a subselect if the where is not empty; otherwise // an unqualified delete or update will work if (sel.getWhere() == null || sel.getWhere().isEmpty()) { sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); return sql; } // we need to use a subselect if we are to bulk delete where // the select includes multiple tables; if the database // doesn't support it, then we need to signal this by returning null if (!supportsSubselect || !supportsCorrelatedSubselect) return null; Column[] pks = mapping.getPrimaryKeyColumns(); sel.clearSelects(); sel.setDistinct(true); // if we have only a single PK, we can use a non-correlated // subquery (using an IN statement), which is much faster than // a correlated subquery (since a correlated subquery needs // to be executed once for each row in the table) if (pks.length == 1) { sel.select(pks[0]); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE "). append(pks[0]).append(" IN ("). append(sel.toSelect(false, null)).append(")"); } else { sel.clearSelects(); sel.setDistinct(false); // since the select is using a correlated subquery, we // only need to select a bogus virtual column sel.select("1", null); // add in the joins to the table Column[] cols = table.getPrimaryKey().getColumns(); SQLBuffer buf = new SQLBuffer(this); buf.append("("); for (int i = 0; i < cols.length; i++) { if (i > 0) buf.append(" AND "); // add in "t0.PK = MYTABLE.PK" buf.append(sel.getColumnAlias(cols[i])).append(" = "). append(table).append(catalogSeparator).append(cols[i]); } buf.append(")"); sel.where(buf, null); sql.append(tableName); appendUpdates(sel, store, sql, params, updateParams, false); sql.append(" WHERE EXISTS ("). append(sel.toSelect(false, null)).append(")"); } return sql; } |
long method | long method | t | t | t | 0 | 6354 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DBDictionary.java/#L2243-L2350 | 1 | 643 | 6354 | critical | ||
| 1400 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | long method | t | t | t | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 1 | 1400 | 10859 | major | ||
| 1348 | YES, I found bad smells. the bad smells are: 1.Inappropriate naming, 2. Long method, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
long method | Inappropriate naming, 2 Long method, 3 Feature envy, 4 Nested conditionals, 5 Mixed levels of abstraction, 6 Repeated code, 7 Data clumps, 8 Primitive obsession | t | f | t | .Inappropriate naming, 3. Feature envy, 4. Nested conditionals, 5. Mixed levels of abstraction, 6. Repeated code, 7. Data clumps, 8. Primitive obsession. | 0 | 10753 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 1348 | 10753 | minor | |
| 765 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class HeaderSection extends UniformItemSection { /** {@code non-null;} the list of the one item in the section */ private final List list; /** * Constructs an instance. The file offset is initially unknown. * * @param file {@code non-null;} file that this instance is part of */ public HeaderSection(DexFile file) { super(null, file, 4); HeaderItem item = new HeaderItem(); item.setIndex(0); this.list = Collections.singletonList(item); } /** {@inheritDoc} */ @Override public IndexedItem get(Constant cst) { return null; } /** {@inheritDoc} */ @Override public Collection items() { return list; } /** {@inheritDoc} */ @Override protected void orderItems() { // Nothing to do here. } } |
data class | data class, long method | t | t | t | long method | 0 | 7136 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/HeaderSection.java/#L27-L62 | 1 | 765 | 7136 | minor | |
| 1239 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10404 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1239 | 10404 | major | ||
| 535 | { "message": "YES I found bad smells", "the bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OperatorWrapper { @SuppressWarnings("unused") private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OperatorWrapper.class); private static final DecimalFormat DECIMAL_FORMATTER = new DecimalFormat("#.##"); private static final String UNKNOWN_OPERATOR = "UNKNOWN_OPERATOR"; //Negative valued constant used for denoting invalid index to indicate absence of metric private static final int NO_SPILL_METRIC_INDEX = Integer.MIN_VALUE; private final int major; private final List, String>> opsAndHosts; // [(operatorProfile --> minorFragment number,host), ...] private final OperatorProfile firstProfile; private final CoreOperatorType operatorType; private final String operatorName; private final int size; private final int timeSkewMin; private final double timeSkewRatio; private final int scanWaitMin; private final double waitSkewRatio; public OperatorWrapper(int major, List, String>> opsAndHostsList, Map phyOperMap, DrillConfig config) { //Threshold to track if the slowest operator ran relatively slow timeSkewMin = config.getInt(ExecConstants.PROFILE_WARNING_TIME_SKEW_MIN); timeSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_PROCESS); //Threshold to track if the slowest SCAN operator spent more time in wait than processing scanWaitMin = config.getInt(ExecConstants.PROFILE_WARNING_SCAN_WAIT_MIN); waitSkewRatio = config.getDouble(ExecConstants.PROFILE_WARNING_TIME_SKEW_RATIO_WAIT); Preconditions.checkArgument(opsAndHostsList.size() > 0); this.major = major; firstProfile = opsAndHostsList.get(0).getLeft().getLeft(); operatorType = CoreOperatorType.valueOf(firstProfile.getOperatorType()); //Update Name from Physical Map String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); //Use Plan Extracted Operator Names if available String extractedOpName = phyOperMap.get(path); String inferredOpName = operatorType == null ? UNKNOWN_OPERATOR : operatorType.toString(); //Revert to inferred names for exceptional cases // 1. Extracted 'FLATTEN' operator is NULL // 2. Extracted 'SCAN' could be a PARQUET_ROW_GROUP_SCAN, or KAFKA_SUB_SCAN, or etc. // 3. Extracted 'UNION_EXCHANGE' could be a SINGLE_SENDER or UNORDERED_RECEIVER if (extractedOpName == null || inferredOpName.contains(extractedOpName) || extractedOpName.endsWith("_EXCHANGE")) { operatorName = inferredOpName; } else { operatorName = extractedOpName; } this.opsAndHosts = opsAndHostsList; size = opsAndHostsList.size(); } public String getDisplayName() { final String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); return String.format("%s - %s", path, operatorName); } public String getId() { return String.format("operator-%d-%d", major, opsAndHosts.get(0).getLeft().getLeft().getOperatorId()); } public static final String [] OPERATOR_COLUMNS = { OperatorTblTxt.MINOR_FRAGMENT, OperatorTblTxt.HOSTNAME, OperatorTblTxt.SETUP_TIME, OperatorTblTxt.PROCESS_TIME, OperatorTblTxt.WAIT_TIME, OperatorTblTxt.MAX_BATCHES, OperatorTblTxt.MAX_RECORDS, OperatorTblTxt.PEAK_MEMORY }; public static final String [] OPERATOR_COLUMNS_TOOLTIP = { OperatorTblTooltip.MINOR_FRAGMENT, OperatorTblTooltip.HOSTNAME, OperatorTblTooltip.SETUP_TIME, OperatorTblTooltip.PROCESS_TIME, OperatorTblTooltip.WAIT_TIME, OperatorTblTooltip.MAX_BATCHES, OperatorTblTooltip.MAX_RECORDS, OperatorTblTooltip.PEAK_MEMORY }; public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS, OPERATOR_COLUMNS_TOOLTIP, true); Map attributeMap = new HashMap<>(); //Reusing for different fragments for (ImmutablePair, String> ip : opsAndHosts) { int minor = ip.getLeft().getRight(); OperatorProfile op = ip.getLeft().getLeft(); attributeMap.put(HtmlAttribute.DATA_ORDER, String.valueOf(minor)); //Overwrite values from previous fragments String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, attributeMap); builder.appendCell(ip.getRight()); builder.appendNanos(op.getSetupNanos()); builder.appendNanos(op.getProcessNanos()); builder.appendNanos(op.getWaitNanos()); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches); builder.appendFormattedInteger(maxRecords); builder.appendBytes(op.getPeakLocalMemoryAllocated()); } return builder.build(); } public static final String[] OPERATORS_OVERVIEW_COLUMNS = { OverviewTblTxt.OPERATOR_ID, OverviewTblTxt.TYPE_OF_OPERATOR, OverviewTblTxt.AVG_SETUP_TIME, OverviewTblTxt.MAX_SETUP_TIME, OverviewTblTxt.AVG_PROCESS_TIME, OverviewTblTxt.MAX_PROCESS_TIME, OverviewTblTxt.MIN_WAIT_TIME, OverviewTblTxt.AVG_WAIT_TIME, OverviewTblTxt.MAX_WAIT_TIME, OverviewTblTxt.PERCENT_FRAGMENT_TIME, OverviewTblTxt.PERCENT_QUERY_TIME, OverviewTblTxt.ROWS, OverviewTblTxt.AVG_PEAK_MEMORY, OverviewTblTxt.MAX_PEAK_MEMORY }; public static final String[] OPERATORS_OVERVIEW_COLUMNS_TOOLTIP = { OverviewTblTooltip.OPERATOR_ID, OverviewTblTooltip.TYPE_OF_OPERATOR, OverviewTblTooltip.AVG_SETUP_TIME, OverviewTblTooltip.MAX_SETUP_TIME, OverviewTblTooltip.AVG_PROCESS_TIME, OverviewTblTooltip.MAX_PROCESS_TIME, OverviewTblTooltip.MIN_WAIT_TIME, OverviewTblTooltip.AVG_WAIT_TIME, OverviewTblTooltip.MAX_WAIT_TIME, OverviewTblTooltip.PERCENT_FRAGMENT_TIME, OverviewTblTooltip.PERCENT_QUERY_TIME, OverviewTblTooltip.ROWS, OverviewTblTooltip.AVG_PEAK_MEMORY, OverviewTblTooltip.MAX_PEAK_MEMORY }; //Palette to help shade operators sharing a common major fragment private static final String[] OPERATOR_OVERVIEW_BGCOLOR_PALETTE = {"#ffffff","#f2f2f2"}; public void addSummary(TableBuilder tb, Map majorFragmentBusyTally, long majorFragmentBusyTallyTotal) { //Select background color from palette String opTblBgColor = OPERATOR_OVERVIEW_BGCOLOR_PALETTE[major%OPERATOR_OVERVIEW_BGCOLOR_PALETTE.length]; String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, opTblBgColor, null); tb.appendCell(operatorName); //Check if spill information is available int spillCycleMetricIndex = getSpillCycleMetricIndex(operatorType); boolean isSpillableOp = (spillCycleMetricIndex != NO_SPILL_METRIC_INDEX); boolean hasSpilledToDisk = false; boolean isScanOp = operatorName.endsWith("SCAN"); //Get MajorFragment Busy+Wait Time Tally long majorBusyNanos = majorFragmentBusyTally.get(new OperatorPathBuilder().setMajor(major).build()); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; double spillCycleSum = 0.0; long spillCycleMax = 0L; long recordSum = 0L; //Construct list for sorting purposes (using legacy Comparators) final List> opList = new ArrayList<>(); for (ImmutablePair,String> ip : opsAndHosts) { OperatorProfile profile = ip.getLeft().getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); for (final StreamProfile sp : profile.getInputProfileList()) { recordSum += sp.getRecords(); } opList.add(ip.getLeft()); //Capture Spill Info //Check to ensure index < #metrics (old profiles have less metrics); else reset isSpillableOp if (isSpillableOp) { //NOTE: We get non-zero value for non-existent metrics, so we can't use getMetric(index) //profile.getMetric(spillCycleMetricIndex).getLongValue(); //Forced to iterate list for (MetricValue metricVal : profile.getMetricList()) { if (metricVal.getMetricId() == spillCycleMetricIndex) { long spillCycles = metricVal.getLongValue(); spillCycleMax = Math.max(spillCycles, spillCycleMax); spillCycleSum += spillCycles; hasSpilledToDisk = (spillCycleSum > 0.0); } } } } final ImmutablePair longSetup = Collections.max(opList, Comparators.setupTime); tb.appendNanos(Math.round(setupSum / size)); tb.appendNanos(longSetup.getLeft().getSetupNanos()); Map timeSkewMap = null; final ImmutablePair longProcess = Collections.max(opList, Comparators.processTime); //Calculating average processing time long avgProcTime = Math.round(processSum / size); tb.appendNanos(avgProcTime); long maxProcTime = longProcess.getLeft().getProcessNanos(); //Calculating skew of longest processing fragment w.r.t. average double maxSkew = (avgProcTime > 0) ? maxProcTime/Double.valueOf(avgProcTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgProcTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > timeSkewRatio ) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment took " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxProcTime, timeSkewMap); final ImmutablePair shortWait = Collections.min(opList, Comparators.waitTime); final ImmutablePair longWait = Collections.max(opList, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos()); //Calculating average wait time for fragment long avgWaitTime = Math.round(waitSum / size); //Slow Scan Warning Map slowScanMap = null; //Marking slow scan if threshold is crossed and wait was longer than processing if (isScanOp && (avgWaitTime > TimeUnit.SECONDS.toNanos(scanWaitMin)) && (avgWaitTime > avgProcTime)) { slowScanMap = new HashMap<>(); slowScanMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SCAN_WAIT_TAG); slowScanMap.put(HtmlAttribute.TITLE, "Avg Wait Time > Avg Processing Time"); slowScanMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(avgWaitTime, slowScanMap); long maxWaitTime = longWait.getLeft().getWaitNanos(); //Skewed Wait Warning timeSkewMap = null; //Resetting //Calculating skew of longest waiting fragment w.r.t. average maxSkew = (avgWaitTime > 0) ? maxWaitTime/Double.valueOf(avgWaitTime) : 0.0d; //Marking skew if both thresholds are crossed if (avgWaitTime > TimeUnit.SECONDS.toNanos(timeSkewMin) && maxSkew > waitSkewRatio) { timeSkewMap = new HashMap<>(); timeSkewMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_TIME_SKEW_TAG); timeSkewMap.put(HtmlAttribute.TITLE, "One fragment waited " + DECIMAL_FORMATTER.format(maxSkew) + " longer than average"); timeSkewMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); } tb.appendNanos(maxWaitTime, timeSkewMap); tb.appendPercent(processSum / majorBusyNanos); tb.appendPercent(processSum / majorFragmentBusyTallyTotal); tb.appendFormattedInteger(recordSum); final ImmutablePair peakMem = Collections.max(opList, Comparators.operatorPeakMemory); //Inject spill-to-disk attributes Map avgSpillMap = null; Map maxSpillMap = null; if (hasSpilledToDisk) { avgSpillMap = new HashMap<>(); //Average SpillCycle double avgSpillCycle = spillCycleSum/size; avgSpillMap.put(HtmlAttribute.TITLE, DECIMAL_FORMATTER.format(avgSpillCycle) + " spills on average"); avgSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); avgSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon avgSpillMap.put(HtmlAttribute.SPILLS, DECIMAL_FORMATTER.format(avgSpillCycle)); //JScript will inject Count maxSpillMap = new HashMap<>(); maxSpillMap.put(HtmlAttribute.TITLE, "Most # spills: " + spillCycleMax); maxSpillMap.put(HtmlAttribute.STYLE, HtmlAttribute.STYLE_VALUE_CURSOR_HELP); maxSpillMap.put(HtmlAttribute.CLASS, HtmlAttribute.CLASS_VALUE_SPILL_TAG); //JScript will inject Icon maxSpillMap.put(HtmlAttribute.SPILLS, String.valueOf(spillCycleMax)); //JScript will inject Count } tb.appendBytes(Math.round(memSum / size), avgSpillMap); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), maxSpillMap); } /** * Returns index of Spill Count/Cycle metric * @param operatorType * @return index of spill metric */ private int getSpillCycleMetricIndex(CoreOperatorType operatorType) { // TODO: DRILL-6642, replace null values for ProtocolMessageEnum with UNRECOGNIZED NullValue to avoid null checks if (operatorType == null) { return NO_SPILL_METRIC_INDEX; } String metricName; switch (operatorType) { case EXTERNAL_SORT: metricName = "SPILL_COUNT"; break; case HASH_AGGREGATE: case HASH_JOIN: metricName = "SPILL_CYCLE"; break; default: return NO_SPILL_METRIC_INDEX; } int metricIndex = 0; //Default String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); for (String name : metricNames) { if (name.equalsIgnoreCase(metricName)) { return metricIndex; } metricIndex++; } //Backward compatibility with rendering older profiles. Ideally we should never touch this if an expected metric is not there return NO_SPILL_METRIC_INDEX; } public String getMetricsTable() { if (operatorType == null) { return ""; } final String[] metricNames = OperatorMetricRegistry.getMetricNames(operatorType.getNumber()); if (metricNames == null) { return ""; } final String[] metricsTableColumnNames = new String[metricNames.length + 1]; metricsTableColumnNames[0] = "Minor Fragment"; int i = 1; for (final String metricName : metricNames) { metricsTableColumnNames[i++] = metricName; } final TableBuilder builder = new TableBuilder(metricsTableColumnNames, null); for (final ImmutablePair,String> ip : opsAndHosts) { final OperatorProfile op = ip.getLeft().getLeft(); builder.appendCell( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getLeft().getRight()) .setOperator(op) .build()); final Number[] values = new Number[metricNames.length]; //Track new/Unknown Metrics final Set unknownMetrics = new TreeSet<>(); for (final MetricValue metric : op.getMetricList()) { if (metric.getMetricId() < metricNames.length) { if (metric.hasLongValue()) { values[metric.getMetricId()] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metric.getMetricId()] = metric.getDoubleValue(); } } else { //Tracking unknown metric IDs unknownMetrics.add(metric.getMetricId()); } } for (final Number value : values) { if (value != null) { builder.appendFormattedNumber(value); } else { builder.appendCell(""); } } } return builder.build(); } private class OperatorTblTxt { static final String MINOR_FRAGMENT = "Minor Fragment"; static final String HOSTNAME = "Hostname"; static final String SETUP_TIME = "Setup Time"; static final String PROCESS_TIME = "Process Time"; static final String WAIT_TIME = "Wait Time"; static final String MAX_BATCHES = "Max Batches"; static final String MAX_RECORDS = "Max Records"; static final String PEAK_MEMORY = "Peak Memory"; } private class OperatorTblTooltip { static final String MINOR_FRAGMENT = "Operator's Minor Fragment"; static final String HOSTNAME = "Host on which the minor fragment ran"; static final String SETUP_TIME = "Setup Time for the minor fragment's operator"; static final String PROCESS_TIME = "Process Time for the minor fragment's operator"; static final String WAIT_TIME = "Wait Time for the minor fragment's operator"; static final String MAX_BATCHES = "Max Batches processed by the minor fragment's operator"; static final String MAX_RECORDS = "Max Records processed by the minor fragment's operator"; static final String PEAK_MEMORY = "Peak Memory usage by the minor fragment's operator"; } private class OverviewTblTxt { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Type"; static final String AVG_SETUP_TIME = "Avg Setup Time"; static final String MAX_SETUP_TIME = "Max Setup Time"; static final String AVG_PROCESS_TIME = "Avg Process Time"; static final String MAX_PROCESS_TIME = "Max Process Time"; static final String MIN_WAIT_TIME = "Min Wait Time"; static final String AVG_WAIT_TIME = "Avg Wait Time"; static final String MAX_WAIT_TIME = "Max Wait Time"; static final String PERCENT_FRAGMENT_TIME = "% Fragment Time"; static final String PERCENT_QUERY_TIME = "% Query Time"; static final String ROWS = "Rows"; static final String AVG_PEAK_MEMORY = "Avg Peak Memory"; static final String MAX_PEAK_MEMORY = "Max Peak Memory"; } private class OverviewTblTooltip { static final String OPERATOR_ID = "Operator ID"; static final String TYPE_OF_OPERATOR = "Operator Type"; static final String AVG_SETUP_TIME = "Average time in setting up fragments"; static final String MAX_SETUP_TIME = "Longest time a fragment took in setup"; static final String AVG_PROCESS_TIME = "Average process time for a fragment"; static final String MAX_PROCESS_TIME = "Longest process time of any fragment"; static final String MIN_WAIT_TIME = "Shortest time a fragment spent in waiting"; static final String AVG_WAIT_TIME = "Average wait time for a fragment"; static final String MAX_WAIT_TIME = "Longest time a fragment spent in waiting"; static final String PERCENT_FRAGMENT_TIME = "Percentage of the total fragment time that was spent on the operator"; static final String PERCENT_QUERY_TIME = "Percentage of the total query time that was spent on the operator"; static final String ROWS = "Rows emitted by scans, or consumed by other operators"; static final String AVG_PEAK_MEMORY = "Average memory consumption by a fragment"; static final String MAX_PEAK_MEMORY = "Highest memory consumption by a fragment"; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 5486 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/server/rest/profile/OperatorWrapper.java/#L43-L442 | 1 | 535 | 5486 | minor | |
| 2005 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 12720 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 2 | 2005 | 12720 | minor | ||
| 2598 | Yes, I found bad smells. The bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 15010 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 2 | 2598 | 15010 | minor | |
| 2480 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity @Table(name = JPADynRealmMembership.TABLE) public class JPADynRealmMembership extends AbstractGeneratedKeyEntity implements DynRealmMembership { private static final long serialVersionUID = 8157856850557493134L; public static final String TABLE = "DynRealmMembership"; @OneToOne private JPADynRealm dynRealm; @ManyToOne private JPAAnyType anyType; @NotNull private String fiql; @Override public DynRealm getDynRealm() { return dynRealm; } @Override public void setDynRealm(final DynRealm dynRealm) { checkType(dynRealm, JPADynRealm.class); this.dynRealm = (JPADynRealm) dynRealm; } @Override public AnyType getAnyType() { return anyType; } @Override public void setAnyType(final AnyType anyType) { checkType(anyType, JPAAnyType.class); this.anyType = (JPAAnyType) anyType; } @Override public String getFIQLCond() { return fiql; } @Override public void setFIQLCond(final String fiql) { this.fiql = fiql; } } |
data class | data class, long method | t | t | t | long method | 0 | 14595 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/core/persistence-jpa/src/main/java/org/apache/syncope/core/persistence/jpa/entity/JPADynRealmMembership.java/#L30-L79 | 1 | 2480 | 14595 | major | |
| 238 | {"response": "YES I found bad smells", "the bad smells are": [ "Long method", "Data class", "Data clumps" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | long method, data class, data clumps | t | t | t | long method, data clumps | 0 | 2613 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 2 | 238 | 2613 | major | |
| 891 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 891 | 8095 | minor | ||
| 2377 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleChainFromFilter( StreamTypeRecord streamType, MethodInvocationTree observableDotFilter, Tree filterMethodOrLambda, VisitorState state) { MethodInvocationTree outerCallInChain = observableDotFilter; if (outerCallInChain == null) { return; } // Traverse the observable call chain out through any pass-through methods do { outerCallInChain = observableOuterCallInChain.get(outerCallInChain); // Check for a map method (which might be a pass-through method or the first method after a // pass-through chain) MethodInvocationTree mapCallsite = observableOuterCallInChain.get(observableDotFilter); if (observableCallToInnerMethodOrLambda.containsKey(outerCallInChain)) { // Update mapToFilterMap Symbol.MethodSymbol mapMethod = ASTHelpers.getSymbol(outerCallInChain); if (streamType.isMapMethod(mapMethod)) { MaplikeToFilterInstanceRecord record = new MaplikeToFilterInstanceRecord( streamType.getMaplikeMethodRecord(mapMethod), filterMethodOrLambda); mapToFilterMap.put(observableCallToInnerMethodOrLambda.get(outerCallInChain), record); } } } while (outerCallInChain != null && streamType.matchesType(ASTHelpers.getReceiverType(outerCallInChain), state) && streamType.isPassthroughMethod(ASTHelpers.getSymbol(outerCallInChain))); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14326 | https://github.com/uber/NullAway/blob/31a184261daaf05f3d353146f44e8e8f12fd7a4d/nullaway/src/main/java/com/uber/nullaway/handlers/RxNullabilityPropagator.java/#L287-L315 | 2 | 2377 | 14326 | minor | ||
| 1832 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JobSchedulerService extends AbstractScheduledService { protected static final long DEFAULT_DELAY = 1000; private static final Logger logger = LoggerFactory.getLogger( JobSchedulerService.class ); private long interval = DEFAULT_DELAY; private int workerSize = 1; private int maxFailCount = 10; private JobAccessor jobAccessor; private JobFactory jobFactory; private Semaphore capacitySemaphore; private ListeningScheduledExecutorService service; private JobListener jobListener; private Timer jobTimer; private Counter runCounter; private Counter successCounter; private Counter failCounter; private Injector injector; //TODO Add meters for throughput of start and stop public JobSchedulerService() { } @Override protected void runOneIteration() throws Exception { MetricsFactory metricsFactory = injector.getInstance( MetricsFactory.class ); jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "scheduler.job_execution_timer" ); runCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.running_workers" ); successCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.successful_jobs" ); failCounter = metricsFactory.getCounter( JobSchedulerService.class, "scheduler.failed_jobs" ); try { if ( logger.isDebugEnabled() ) { logger.debug( "Running one check iteration ..." ); } List activeJobs; // run until there are no more active jobs while ( true ) { // get the semaphore if we can. This means we have space for at least 1 // job if ( logger.isDebugEnabled() ) { logger.debug( "About to acquire semaphore. Capacity is {}", capacitySemaphore.availablePermits() ); } capacitySemaphore.acquire(); // release the sempaphore we only need to acquire as a way to stop the // loop if there's no capacity capacitySemaphore.release(); int capacity = capacitySemaphore.availablePermits(); if (logger.isDebugEnabled()) { logger.debug("Capacity is {}", capacity); } activeJobs = jobAccessor.getJobs( capacity ); // nothing to do, we don't have any jobs to run if ( activeJobs.size() == 0 ) { if (logger.isDebugEnabled()) { logger.debug("No jobs returned. Exiting run loop"); } return; } for ( JobDescriptor jd : activeJobs ) { logger.debug( "Submitting work for {}", jd ); submitWork( jd ); logger.debug( "Work submitted for {}", jd ); } } } catch ( Throwable t ) { if (logger.isDebugEnabled()) { logger.debug("Scheduler run failed, error is", t); } } } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#scheduler() */ @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule( 0, interval, TimeUnit.MILLISECONDS ); } /** * Use the provided BulkJobFactory to build and submit BulkJob items as ListenableFuture objects */ private void submitWork( final JobDescriptor jobDescriptor ) { final Job job; try { job = jobFactory.jobsFrom( jobDescriptor ); } catch ( JobNotFoundException e ) { logger.error( "Could not create jobs", e ); return; } // job execution needs to be external to both the callback and the task. // This way regardless of any error we can // mark a job as failed if required final JobExecution execution = new JobExecutionImpl( jobDescriptor ); // We don't care if this is atomic (not worth using a lock object) // we just need to prevent NPEs from ever occurring final JobListener currentListener = this.jobListener; /** * Acquire the semaphore before we schedule. This way we wont' take things from the Q that end up * stuck in the queue for the scheduler and then time out their distributed heartbeat */ try { capacitySemaphore.acquire(); } catch ( InterruptedException e ) { logger.error( "Unable to acquire semaphore capacity before submitting job", e ); //just return, they'll get picked up again later return; } final Timer.Context timer = jobTimer.time(); ListenableFuture future = service.submit( new Callable() { @Override public Void call() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Starting the job with job id {}", execution.getJobId()); } runCounter.inc(); execution.start( maxFailCount ); //this job is dead, treat it as such if ( execution.getStatus() == Status.DEAD ) { try { job.dead( execution ); jobAccessor.save( execution ); } catch ( Exception t ) { //we purposefully swallow all exceptions here, we don't want it to effect the outcome //of finally popping this job from the queue logger.error( "Unable to invoke dead event on job", t ); } return null; } jobAccessor.save( execution ); // TODO wrap and throw specifically typed exception for onFailure, // needs jobId logger.debug( "Starting job {} with execution data {}", job, execution ); job.execute( execution ); if ( currentListener != null ) { currentListener.onSubmit( execution ); } return null; } } ); Futures.addCallback( future, new FutureCallback() { @Override public void onSuccess( Void param ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ if (logger.isDebugEnabled()) { logger.debug("Job succeeded with the job id {}", execution.getJobId()); } capacitySemaphore.release(); timer.stop(); runCounter.dec(); successCounter.inc(); //TODO, refactor into the execution itself for checking if done if ( execution.getStatus() == Status.IN_PROGRESS ) { logger.debug( "Successful completion of bulkJob {}", execution ); execution.completed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onSuccess( execution ); } } @Override public void onFailure( Throwable throwable ) { /** * Release semaphore first in case there are other problems with communicating with Cassandra */ logger.error( "Job failed with the job id {}", execution.getJobId() ); capacitySemaphore.release(); timer.stop(); runCounter.dec(); failCounter.inc(); logger.error( "Failed execution for bulkJob", throwable ); // mark it as failed if ( execution.getStatus() == Status.IN_PROGRESS ) { execution.failed(); } jobAccessor.save( execution ); if ( currentListener != null ) { currentListener.onFailure( execution ); } } } ); } /** * @param milliseconds the milliseconds to set to wait if we didn't receive a job to run */ public void setInterval( long milliseconds ) { this.interval = milliseconds; } public long getInterval() { return interval; } /** * @param listeners the listeners to set */ public void setWorkerSize( int listeners ) { this.workerSize = listeners; } public int getWorkerSize() { return workerSize; } /** * @param jobAccessor the jobAccessor to set */ public void setJobAccessor( JobAccessor jobAccessor ) { this.jobAccessor = jobAccessor; } /** * @param jobFactory the jobFactory to set */ public void setJobFactory( JobFactory jobFactory ) { this.jobFactory = jobFactory; } /** * @param maxFailCount the maxFailCount to set */ public void setMaxFailCount( int maxFailCount ) { this.maxFailCount = maxFailCount; } /** * Set the metrics factory */ // public void setMetricsFactory( MetricsFactory metricsFactory ) { // // jobTimer = metricsFactory.getTimer( JobSchedulerService.class, "job_execution_timer" ); // runCounter = metricsFactory.getCounter( JobSchedulerService.class, "running_workers" ); // successCounter = metricsFactory.getCounter( JobSchedulerService.class, "successful_jobs" ); // failCounter = metricsFactory.getCounter( JobSchedulerService.class, "failed_jobs" ); // } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#startUp() */ @Override protected void startUp() throws Exception { service = MoreExecutors .listeningDecorator( Executors.newScheduledThreadPool( workerSize, JobThreadFactory.INSTANCE ) ); capacitySemaphore = new Semaphore( workerSize ); logger.info( "Starting executor pool. Capacity is {}", workerSize ); super.startUp(); logger.info( "Job Scheduler started" ); } /* * (non-Javadoc) * * @see com.google.common.util.concurrent.AbstractScheduledService#shutDown() */ @Override protected void shutDown() throws Exception { logger.info( "Shutting down job scheduler" ); service.shutdown(); logger.info( "Job scheduler shut down" ); super.shutDown(); } /** * Sets the JobListener notified of Job events on this SchedulerService. * * @param jobListener the listener to receive Job events * * @return the previous listener if set, or null if none was set */ public JobListener setJobListener( JobListener jobListener ) { JobListener old = this.jobListener; this.jobListener = jobListener; return old; } /** * Gets the current JobListener to be notified of Job events on this SchedulerService. * * @return the current JobListener or null if none was set */ public JobListener getJobListener() { return jobListener; } public void setInjector(Injector injector) { this.injector = injector; } /** * Simple factory for labeling job worker threads for easier debugging */ private static final class JobThreadFactory implements ThreadFactory { public static final JobThreadFactory INSTANCE = new JobThreadFactory(); private static final String NAME = "JobWorker-"; private final AtomicLong counter = new AtomicLong(); @Override public Thread newThread( final Runnable r ) { Thread newThread = new Thread( r, NAME + counter.incrementAndGet() ); newThread.setDaemon( true ); return newThread; } } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12128 | https://github.com/apache/usergrid/blob/ac1e6e4035f9307b871478ed47246cf92cfd5f7f/stack/core/src/main/java/org/apache/usergrid/batch/service/JobSchedulerService.java/#L55-L450 | 1 | 1832 | 12128 | minor | |
| 869 | YES I found bad smells: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Feature envy | t | f | t | 0 | 7948 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 869 | 7948 | major | ||
| 32 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Build { /** * Project version. */ private String version = ""; public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } } |
data class | data class | t | t | t | 0 | 730 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java/#L75-L90 | 1 | 32 | 730 | critical | ||
| 2251 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("all") public class Case_1 { @Accessors private int id; public int testFunction1() { return 42; } public int testFunction2() { return 42; } public Integer testFunction3() { return Integer.valueOf(42); } @Pure public int getId() { return this.id; } public void setId(final int id) { this.id = id; } } |
data class | long method, data class | t | t | t | long method | 0 | 13674 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core.tests/longrunning/xtend-gen/org/eclipse/xtend/core/tests/smoke/Case_1.java/#L6-L31 | 1 | 2251 | 13674 | minor | |
| 1103 | {"response": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static void copyDirectory(final File srcDir, final File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (!srcDir.exists()) { throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); } if (!srcDir.isDirectory()) { throw new IOException("Source '" + srcDir + "' exists but is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // Cater for destination being directory within the source directory (see IO-141) List exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { final File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<>(srcFiles.length); for (final File srcFile : srcFiles) { final File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, exclusionList); } |
long method | 1. long method | t | t | t | 0 | 9847 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-loader/src/main/java/org/apache/openejb/loader/IO.java/#L193-L223 | 1 | 1103 | 9847 | minor | ||
| 1110 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RabbitGatewaySupport implements InitializingBean { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR private RabbitOperations rabbitOperations; /** * Set the Rabbit connection factory to be used by the gateway. * Will automatically create a RabbitTemplate for the given ConnectionFactory. * @param connectionFactory The connection factory. * @see #createRabbitTemplate * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setConnectionFactory(ConnectionFactory connectionFactory) { this.rabbitOperations = createRabbitTemplate(connectionFactory); } /** * Create a RabbitTemplate for the given ConnectionFactory. * Only invoked if populating the gateway with a ConnectionFactory reference. * * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for * @return the new RabbitTemplate instance * @see #setConnectionFactory */ protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } /** * @return The Rabbit ConnectionFactory used by the gateway. */ @Nullable public final ConnectionFactory getConnectionFactory() { return (this.rabbitOperations != null ? this.rabbitOperations.getConnectionFactory() : null); } /** * Set the {@link RabbitOperations} for the gateway. * @param rabbitOperations The Rabbit operations. * @see #setConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) */ public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); } try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } } |
blob | blob | t | t | t | 0 | 9884 | https://github.com/spring-projects/spring-amqp/blob/1614a4b0532b83e29b2a2fdb8dac102576b8aa51/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitGatewaySupport.java/#L43-L117 | 1 | 1110 | 9884 | minor | ||
| 1211 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 10310 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 1211 | 10310 | critical | ||
| 2915 | YES I found bad smells the bad smells are: 1. Long method 2. Repeated code (saveState) 3. Feature envy (multiple method calls on different objects) 4. Inefficient use of flag variables 5. Unused code (clearAttributes() not currently necessary) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean incrementToken() throws IOException { for(;;) { if (!remainingTokens.isEmpty()) { // clearAttributes(); // not currently necessary restoreState(remainingTokens.removeFirst()); return true; } if (!input.incrementToken()) return false; int len = termAtt.length(); if (len==0) return true; // pass through zero length terms int firstAlternativeIncrement = inject ? 0 : posAtt.getPositionIncrement(); String v = termAtt.toString(); String primaryPhoneticValue = encoder.doubleMetaphone(v); String alternatePhoneticValue = encoder.doubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. boolean saveState=inject; if (primaryPhoneticValue!=null && primaryPhoneticValue.length() > 0 && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); } posAtt.setPositionIncrement( firstAlternativeIncrement ); firstAlternativeIncrement = 0; termAtt.setEmpty().append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue!=null && alternatePhoneticValue.length() > 0 && !alternatePhoneticValue.equals(primaryPhoneticValue) && !primaryPhoneticValue.equals(v)) { if (saveState) { remainingTokens.addLast(captureState()); saveState = false; } posAtt.setPositionIncrement( firstAlternativeIncrement ); termAtt.setEmpty().append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.isEmpty()) { return true; } if (saveState) { remainingTokens.addLast(captureState()); } } } |
long method | Long method2 Repeated code (saveState)3 Feature envy (multiple method calls on different objects)4 Inefficient use of flag variables5 Unused code (clearAttributes() not currently necessary) | t | f | t | 0 | 2253 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/phonetic/src/java/org/apache/lucene/analysis/phonetic/DoubleMetaphoneFilter.java/#L51-L108 | 2 | 2915 | 2253 | major | ||
| 993 | {"message": "YES I found bad smells", "bad_smells_list": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public int compare(PropertyDescriptor d1, PropertyDescriptor d2) { String g1 = group(d1); String g2 = group(d2); Integer go1 = groupOrder(g1); Integer go2 = groupOrder(g2); int result = go1.compareTo(go2); if (result != 0) { return result; } result = g1.compareTo(g2); if (result != 0) { return result; } Integer po1 = propertyOrder(d1); Integer po2 = propertyOrder(d2); result = po1.compareTo(po2); if (result != 0) { return result; } return d1.getName().compareTo(d2.getName()); } |
long method | long method | t | t | t | 0 | 9070 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/core/org/apache/jmeter/testbeans/gui/GenericTestBeanCustomizer.java/#L674-L699 | 1 | 993 | 9070 | minor | ||
| 2666 | YES, I found bad smellsthe bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static int reconfigureNetworking() { // This uses values from the property settings if (Sage.getBoolean(NET_CONFIG_WIRED, true)) { // Bring down the wireless interface if it's there bringDownWireless(); setupNetworking(Sage.get("linux/wired_network_port", "eth0")); } else { // Bring down the wired interface if it's there if (Sage.getBoolean("linux/disable_wired_when_wireless_is_enabled", false)) bringDownWired(); // Be sure the wired interface is loaded (it may need to be before it is configured) IOUtils.exec2("ifconfig " + Sage.get("linux/wireless_network_port", "eth1") + " up"); // Setup the wireless networking properties before we try to connect to the network or it won't work IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " essid " + Sage.get(NET_CONFIG_SSID, "any")); String crypto = Sage.get(NET_CONFIG_ENCRYPTION, "WPA"); if ("None".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key off"); } else { // Check if the key is all hex String key = Sage.get(NET_CONFIG_ENCRYPTION_KEY, ""); boolean hexKey = true; for (int i = 0; i < key.length(); i++) { if (Character.digit(key.charAt(i), 16) < 0) { hexKey = false; break; } } if ("WEP".equals(crypto)) { IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key on"); if (hexKey) IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key " + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); else IOUtils.exec2("iwconfig " + Sage.get("linux/wireless_network_port", "eth1") + " key s:" + Sage.get(NET_CONFIG_ENCRYPTION_KEY, "")); } else // WPA { // NOT FINISHED YET, we'll need to setup a configuration file for wpa_supplicant and then run it } } setupNetworking(Sage.get("linux/wireless_network_port", "eth1")); } return 0; } |
long method | Long method | t | f | t | 0 | 15203 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/LinuxUtils.java/#L51-L108 | 2 | 2666 | 15203 | major | ||
| 2050 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.alias == null ? 0 : this.alias.hashCode()); result = prime * result + (this.ciphers == null ? 0 : this.ciphers.hashCode()); result = prime * result + (this.hostnameVerification ? 1231 : 1237); result = prime * result + (this.keyStore == null ? 0 : this.keyStore.hashCode()); result = prime * result + Arrays.hashCode(this.keyStorePassword); result = prime * result + (this.protocol == null ? 0 : this.protocol.hashCode()); result = prime * result + (this.sslManagerOpts == null ? 0 : this.sslManagerOpts.hashCode()); result = prime * result + (this.trustStore == null ? 0 : this.trustStore.hashCode()); return result; } |
long method | Long method2 Feature envy | t | f | t | 0 | 12885 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.core/src/main/java/org/eclipse/kura/core/ssl/ConnectionSslOptions.java/#L107-L120 | 2 | 2050 | 12885 | minor | ||
| 992 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | 1. long method | t | t | t | 0 | 9038 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 992 | 9038 | minor | ||
| 2131 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addDataAccessNodes(UaFolderNode rootNode) { // DataAccess folder UaFolderNode dataAccessFolder = new UaFolderNode( getNodeContext(), newNodeId("HelloWorld/DataAccess"), newQualifiedName("DataAccess"), LocalizedText.english("DataAccess") ); getNodeManager().addNode(dataAccessFolder); rootNode.addOrganizes(dataAccessFolder); // AnalogItemType node try { AnalogItemNode node = (AnalogItemNode) getNodeFactory().createNode( newNodeId("HelloWorld/DataAccess/AnalogValue"), Identifiers.AnalogItemType, true ); node.setBrowseName(newQualifiedName("AnalogValue")); node.setDisplayName(LocalizedText.english("AnalogValue")); node.setDataType(Identifiers.Double); node.setValue(new DataValue(new Variant(3.14d))); node.setEURange(new Range(0.0, 100.0)); getNodeManager().addNode(node); dataAccessFolder.addOrganizes(node); } catch (UaException e) { logger.error("Error creating AnalogItemType instance: {}", e.getMessage(), e); } } |
long method | long method, data class | t | t | t | data class | 0 | 13232 | https://github.com/eclipse/milo/blob/e752e540d31eb3c226e6e79dd197c54d7d254685/milo-examples/server-examples/src/main/java/org/eclipse/milo/examples/server/ExampleNamespace.java/#L503-L535 | 1 | 2131 | 13232 | minor | |
| 258 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 2 | 258 | 2807 | minor | |
| 20 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MachineStoppedEvent extends GwtEvent { public static final Type TYPE = new Type<>(); private final MachineImpl machine; public MachineStoppedEvent(MachineImpl machine) { this.machine = machine; } /** Returns the stopped machine. */ public MachineImpl getMachine() { return machine; } @Override public Type getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onMachineStopped(this); } public interface Handler extends EventHandler { void onMachineStopped(MachineStoppedEvent event); } } |
data class | data class | t | t | t | 0 | 681 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/event/MachineStoppedEvent.java/#L19-L47 | 1 | 20 | 681 | minor | ||
| 492 | { "response": "YES I found bad smells", "bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class WizardUIInfoPage { private int order; private String description; public int getOrder() { return order; } public String getDescription() { return description; } public static WizardUIInfoPage getDefaultPage(int order) { WizardUIInfoPage page = new WizardUIInfoPage(); page.order = order; page.description = ""; return page; } } |
data class | 1. data class | t | t | f | data class | 0 | 4936 | https://github.com/spring-projects/spring-ide/blob/915fe9bffd50db45ee0b8fb993416e45dee68179/plugins/org.springframework.ide.eclipse.wizard/src/org/springframework/ide/eclipse/wizard/template/infrastructure/ui/WizardUIInfoPage.java/#L18-L39 | 1 | 492 | 4936 | minor | |
| 2644 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void weaveDir(File dir, String consumerHeaderKey, String consumerHeaderValue, String bundleClassPath) throws Exception { Set wd = ConsumerHeaderProcessor.processHeader(consumerHeaderKey, consumerHeaderValue); URLClassLoader cl = new URLClassLoader(new URL [] {dir.toURI().toURL()}, Main.class.getClassLoader()); String dirName = dir.getAbsolutePath(); DirTree dt = new DirTree(dir); for (File f : dt.getFiles()) { if (!f.getName().endsWith(".class")) continue; String className = f.getAbsolutePath().substring(dirName.length()); if (className.startsWith(File.separator)) className = className.substring(1); className = className.substring(0, className.length() - ".class".length()); className = className.replace(File.separator, "."); InputStream is = new FileInputStream(f); byte[] b; try { ClassReader cr = new ClassReader(is); ClassWriter cw = new StaticToolClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, cl); TCCLSetterVisitor cv = new TCCLSetterVisitor(cw, className, wd); cr.accept(cv, ClassReader.SKIP_FRAMES); if (cv.isWoven()) { b = cw.toByteArray(); } else { // if not woven, store the original bytes b = Streams.suck(new FileInputStream(f)); } } finally { is.close(); } OutputStream os = new FileOutputStream(f); try { os.write(b); } finally { os.close(); } } if (bundleClassPath != null) { for (String entry : bundleClassPath.split(",")) { File jarFile = new File(dir, entry.trim()); if (jarFile.isFile()) { weaveBCPJar(jarFile, consumerHeaderKey, consumerHeaderValue); } } } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15149 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/spi-fly/spi-fly-static-tool/src/main/java/org/apache/aries/spifly/statictool/Main.java/#L173-L223 | 2 | 2644 | 15149 | major | ||
| 940 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void doDefensiveChecks(DistribPhase phase) { boolean isReplayOrPeersync = (updateCommand.getFlags() & (UpdateCommand.REPLAY | UpdateCommand.PEER_SYNC)) != 0; if (isReplayOrPeersync) return; String from = req.getParams().get(DISTRIB_FROM); ClusterState clusterState = zkController.getClusterState(); DocCollection docCollection = clusterState.getCollection(collection); Slice mySlice = docCollection.getSlice(cloudDesc.getShardId()); boolean localIsLeader = cloudDesc.isLeader(); if (DistribPhase.FROMLEADER == phase && localIsLeader && from != null) { // from will be null on log replay String fromShard = req.getParams().get(DISTRIB_FROM_PARENT); if (fromShard != null) { if (mySlice.getState() == Slice.State.ACTIVE) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but we are in active state"); } // shard splitting case -- check ranges to see if we are a sub-shard Slice fromSlice = docCollection.getSlice(fromShard); DocRouter.Range parentRange = fromSlice.getRange(); if (parentRange == null) parentRange = new DocRouter.Range(Integer.MIN_VALUE, Integer.MAX_VALUE); if (mySlice.getRange() != null && !mySlice.getRange().isSubsetOf(parentRange)) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from parent shard leader but parent hash range is not superset of my range"); } } else { String fromCollection = req.getParams().get(DISTRIB_FROM_COLLECTION); // is it because of a routing rule? if (fromCollection == null) { log.error("Request says it is coming from leader, but we are the leader: " + req.getParamString()); SolrException solrExc = new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Request says it is coming from leader, but we are the leader"); solrExc.setMetadata("cause", "LeaderChanged"); throw solrExc; } } } int count = 0; while (((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) && count < 5) { count++; // re-getting localIsLeader since we published to ZK first before setting localIsLeader value localIsLeader = cloudDesc.isLeader(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if ((isLeader && !localIsLeader) || (isSubShardLeader && !localIsLeader)) { log.error("ClusterState says we are the leader, but locally we don't think so"); throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader (" + zkController.getBaseUrl() + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8460 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/update/processor/DistributedZkUpdateProcessor.java/#L953-L1007 | 2 | 940 | 8460 | major | |
| 922 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processAsSubstitutableExport(boolean isFragment, Requirement requirement, List capabilities) { String namespace = requirement.getNamespace(); if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return; } Resource resource = requirement.getResource(); Wiring wiring = wirings.get(resource); if (isFragment) { List fragmentWires = wiring.getRequiredResourceWires(HostNamespace.HOST_NAMESPACE); for (Wire fragmentWire : fragmentWires) { Resource host = fragmentWire.getProvider(); processResourceCapabilities( wirings.get(host).getResourceCapabilities(namespace), requirement, capabilities); } } else { List resourceCapabilities = wiring.getResourceCapabilities(namespace); processResourceCapabilities(resourceCapabilities, requirement, capabilities); } } |
long method | long method | t | t | t | 0 | 8279 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/internal/ResolveContext.java/#L158-L179 | 1 | 922 | 8279 | minor | ||
| 1774 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SpringComponent @VaadinSessionScope public class ManageSoftwareModuleFilters implements Serializable { private static final long serialVersionUID = -1631725636290496525L; private SoftwareModuleType softwareModuleType; private String searchText; /** * @return the softwareModuleType */ public Optional getSoftwareModuleType() { return Optional.ofNullable(softwareModuleType); } /** * @param softwareModuleType * the softwareModuleType to set */ public void setSoftwareModuleType(final SoftwareModuleType softwareModuleType) { this.softwareModuleType = softwareModuleType; } /** * @return the searchText */ public Optional getSearchText() { return Optional.ofNullable(searchText); } /** * @param searchText * the searchText to set */ public void setSearchText(final String searchText) { this.searchText = searchText; } } |
data class | data class | t | t | t | 0 | 11932 | https://github.com/eclipse/hawkbit/blob/51be28147f6f575b6c1ab4a5ef84ffd9174f1209/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageSoftwareModuleFilters.java/#L23-L62 | 1 | 1774 | 11932 | minor | ||
| 1443 | { "message": "YES I found bad smells", "bad smells are": ["Long Method", "Feature Envy"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void writeJSON( final Writer pw, final ServiceReference service, final boolean fullDetails, final Locale locale, final String filter ) throws IOException { final ServiceReference[] allServices = this.getServices(filter); final String statusLine = getStatusLine( allServices ); final ServiceReference[] services = ( service != null ) ? new ServiceReference[] { service } : allServices; final JSONWriter jw = new JSONWriter( pw ); jw.object(); jw.key( "status" ); jw.value( statusLine ); jw.key( "serviceCount" ); jw.value( allServices.length ); jw.key( "data" ); jw.array(); for ( int i = 0; i < services.length; i++ ) { serviceInfo( jw, services[i], fullDetails || service != null, locale ); } jw.endArray(); jw.endObject(); } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10977 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/ServicesServlet.java/#L342-L374 | 1 | 1443 | 10977 | minor | |
| 2164 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SocketServer(NetworkConfig config, SSLConfig sslConfig, MetricRegistry registry, ArrayList portList) { this.host = config.hostName; this.port = config.port; this.numProcessorThreads = config.numIoThreads; this.maxQueuedRequests = config.queuedMaxRequests; this.sendBufferSize = config.socketSendBufferBytes; this.recvBufferSize = config.socketReceiveBufferBytes; this.maxRequestSize = config.socketRequestMaxBytes; processors = new ArrayList(numProcessorThreads); requestResponseChannel = new SocketRequestResponseChannel(numProcessorThreads, maxQueuedRequests); metrics = new ServerNetworkMetrics(requestResponseChannel, registry, processors); this.acceptors = new ArrayList(); this.ports = new HashMap(); this.validatePorts(portList); this.initializeSSLFactory(sslConfig); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13339 | https://github.com/linkedin/ambry/blob/1d2e455556058b83f5145740b7f2c5772fa37e1b/ambry-network/src/main/java/com.github.ambry.network/SocketServer.java/#L67-L82 | 2 | 2164 | 13339 | minor | ||
| 125 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class NotificationsAggregatorState { public long recentEventLogsCount; public long activeRequestsCount; } |
data class | data class | t | t | t | 0 | 1573 | https://github.com/vmware/admiral/blob/e02d0e77f65d0ee3541a378110ecd4233bdb6664/request/src/main/java/com/vmware/admiral/request/notification/NotificationsService.java/#L52-L55 | 1 | 125 | 1573 | critical | ||
| 1698 | { "response": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @InterfaceStability.Evolving public class BlockMissingException extends IOException { private static final long serialVersionUID = 1L; private String filename; private long offset; /** * An exception that indicates that file was corrupted. * @param filename name of corrupted file * @param description a description of the corruption details */ public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } /** * Returns the name of the corrupted file. * @return name of corrupted file */ public String getFile() { return filename; } /** * Returns the offset at which this file is corrupted * @return offset of corrupted file */ public long getOffset() { return offset; } } |
data class | 1 Data Class | t | f | t | 0 | 11733 | https://github.com/apache/hadoop-hdfs/blob/b2d2a3262c587638db04c2991d48656b3d06275c/src/java/org/apache/hadoop/hdfs/BlockMissingException.java/#L30-L65 | 1 | 1698 | 11733 | minor | ||
| 366 | YES I found bad smells the bad smells are: 1. Long method 2. Method with multiple responsibilities 3. Feature envy 4. Code duplication (the for loop that allocates columns could be extracted into a separate method) 5. Lack of comments/documentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected VectorizedRowBatch setupOverflowBatch() throws HiveException { int initialColumnCount = vContext.firstOutputColumnIndex(); VectorizedRowBatch overflowBatch; int totalNumColumns = initialColumnCount + vOutContext.getScratchColumnTypeNames().length; overflowBatch = new VectorizedRowBatch(totalNumColumns); // First, just allocate just the output columns we will be using. for (int i = 0; i < outputProjectionColumnMap.length; i++) { int outputColumn = outputProjectionColumnMap[i]; String typeName = outputTypeInfos[i].getTypeName(); allocateOverflowBatchColumnVector(overflowBatch, outputColumn, typeName); } // Now, add any scratch columns needed for children operators. int outputColumn = initialColumnCount; for (String typeName : vOutContext.getScratchColumnTypeNames()) { allocateOverflowBatchColumnVector(overflowBatch, outputColumn++, typeName); } overflowBatch.projectedColumns = outputProjectionColumnMap; overflowBatch.projectionSize = outputProjectionColumnMap.length; overflowBatch.reset(); return overflowBatch; } |
long method | Long method2 Method with multiple responsibilities3 Feature envy4 Code duplication (the for loop that allocates columns could be extracted into a separate method)5 Lack of comments/documentation | t | f | t | 0 | 3740 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFOperator.java/#L241-L268 | 2 | 366 | 3740 | minor | ||
| 2328 | YES I found bad smells the bad smells are: 1. Long method 2. Primitive obsession 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public DirectWriteRolloverStrategy build() { int maxIndex = Integer.MAX_VALUE; if (maxFiles != null) { maxIndex = Integer.parseInt(maxFiles); if (maxIndex < 0) { maxIndex = Integer.MAX_VALUE; } else if (maxIndex < 2) { LOGGER.error("Maximum files too small. Limited to " + DEFAULT_MAX_FILES); maxIndex = DEFAULT_MAX_FILES; } } final int compressionLevel = Integers.parseInt(compressionLevelStr, Deflater.DEFAULT_COMPRESSION); return new DirectWriteRolloverStrategy(maxIndex, compressionLevel, config.getStrSubstitutor(), customActions, stopCustomActionsOnError, tempCompressedFilePattern); } |
feature envy | Long method 2 Primitive obsession 3 Feature envy | t | f | t | 0 | 14146 | https://github.com/apache/logging-log4j2/blob/9b6bb237ae8771ffbf6d61ed07b0acb4f4dc2da6/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectWriteRolloverStrategy.java/#L84-L99 | 2 | 2328 | 14146 | minor | ||
| 1672 | YES I found bad smells 1. Long method 2. Data class 3. Shotgun surgery 4. Inappropriate intimacy 5. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | Long method2 Data class3 Shotgun surgery4 Inappropriate intimacy5 Feature envy | t | f | t | 0 | 11637 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 2 | 1672 | 11637 | minor | ||
| 489 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void appendXmlComparison1(SQLBuffer buf, String op, FilterValue lhs, FilterValue rhs) { boolean castrhs = false; Class rc = Filters.wrap(rhs.getType()); int type = 0; if (rhs.isConstant()) { type = getJDBCType(JavaTypes.getTypeCode(rc), false); castrhs = true; } appendXmlExists(buf, lhs); buf.append(" ").append(op).append(" "); buf.append("$"); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("]' PASSING "); appendXmlVar(buf, lhs); buf.append(", "); if (castrhs) appendCast(buf, rhs, type); else rhs.appendTo(buf); buf.append(" AS \""); if (castrhs) buf.append("Parm"); else rhs.appendTo(buf); buf.append("\")"); } |
long method | long method, blob | t | t | t | blob | 0 | 4865 | https://github.com/apache/openjpa/blob/8c0b843f6e6e0dd86a31e485928e61f2ba4c8f29/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/DB2Dictionary.java/#L682-L717 | 1 | 489 | 4865 | minor | |
| 608 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ReferenceProperty implements Property { EntityReference reference; public ReferenceProperty() { } public ReferenceProperty( EntityReference reference ) { this.reference = reference; } @Override public EntityReference get() { return reference; } @Override public void set( EntityReference newValue ) throws IllegalArgumentException, IllegalStateException { reference = newValue; } } |
data class | data class, long method | t | t | t | long method | 0 | 6114 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/runtime/src/main/java/org/apache/polygene/runtime/value/ReferenceProperty.java/#L28-L54 | 1 | 608 | 6114 | major | |
| 2656 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ElementImpl extends MinimalEObjectImpl.Container implements Element { /** * The default value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected static final boolean A_EDEFAULT = false; /** * The cached value of the '{@link #isA() A}' attribute. * * * @see #isA() * @generated * @ordered */ protected boolean a = A_EDEFAULT; /** * The default value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() Name}' attribute. * * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getElements() Elements}' containment reference list. * * * @see #getElements() * @generated * @ordered */ protected EList elements; /** * * * @generated */ protected ElementImpl() { super(); } /** * * * @generated */ @Override protected EClass eStaticClass() { return Bug305397Package.Literals.ELEMENT; } /** * * * @generated */ public boolean isA() { return a; } /** * * * @generated */ public void setA(boolean newA) { boolean oldA = a; a = newA; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__A, oldA, a)); } /** * * * @generated */ public String getName() { return name; } /** * * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bug305397Package.ELEMENT__NAME, oldName, name)); } /** * * * @generated */ public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(Element.class, this, Bug305397Package.ELEMENT__ELEMENTS); } return elements; } /** * * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bug305397Package.ELEMENT__ELEMENTS: return ((InternalEList)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bug305397Package.ELEMENT__A: return isA(); case Bug305397Package.ELEMENT__NAME: return getName(); case Bug305397Package.ELEMENT__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA((Boolean)newValue); return; case Bug305397Package.ELEMENT__NAME: setName((String)newValue); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); getElements().addAll((Collection)newValue); return; } super.eSet(featureID, newValue); } /** * * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: setA(A_EDEFAULT); return; case Bug305397Package.ELEMENT__NAME: setName(NAME_EDEFAULT); return; case Bug305397Package.ELEMENT__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bug305397Package.ELEMENT__A: return a != A_EDEFAULT; case Bug305397Package.ELEMENT__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case Bug305397Package.ELEMENT__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } /** * * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (a: "); result.append(a); result.append(", name: "); result.append(name); result.append(')'); return result.toString(); } } //ElementImpl |
data class | data class | t | t | t | 0 | 15183 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parsetree/impl/bug305397/impl/ElementImpl.java/#L40-L296 | 1 | 2656 | 15183 | minor | ||
| 2781 | {"message": "YES I found bad smells", "bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: /* update subject DN */ subjectDN = cert.getSubjectX500Principal(); /* check for key needing to inherit alg parameters */ X509CertImpl icert = X509CertImpl.toImpl(cert); PublicKey newKey = cert.getPublicKey(); if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); } /* update subject public key */ pubKey = newKey; /* * if this is a trusted cert (init == true), then we * don't update any of the remaining fields */ if (init) { init = false; return; } /* update subject key identifier */ subjKeyId = icert.getSubjectKeyIdentifierExtension(); /* update crlSign */ crlSign = RevocationChecker.certCanSignCrl(cert); /* update current name constraints */ if (nc != null) { nc.merge(icert.getNameConstraintsExtension()); } else { nc = icert.getNameConstraintsExtension(); if (nc != null) { // Make sure we do a clone here, because we're probably // going to modify this object later and we don't want to // be sharing it with a Certificate object! nc = (NameConstraintsExtension) nc.clone(); } } /* update policy state variables */ explicitPolicy = PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); policyMapping = PolicyChecker.mergePolicyMapping(policyMapping, icert); inhibitAnyPolicy = PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); certIndex++; /* * Update remaining CA certs */ remainingCACerts = ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); init = false; } /** * Returns a boolean flag indicating if a key lacking necessary key * algorithm parameters has been encountered. * * @return boolean flag indicating if key lacking parameters encountered. */ |
long method | long method | t | t | t | 0 | 1122 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/provider/certpath/ReverseState.java/#L284-L348 | 1 | 2781 | 1122 | major | ||
| 3795 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String toString() { StringBuilder sb = new StringBuilder(); sb.append(Constants.INDENT); sb.append("kdf: 0x"); sb.append(Functions.toFullHexString(kdf)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedDataLen: "); sb.append(pSharedData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pSharedData: "); sb.append(Functions.toHexString(pSharedData)); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicDataLen: "); sb.append(pPublicData.length); sb.append(Constants.NEWLINE); sb.append(Constants.INDENT); sb.append("pPublicData: "); sb.append(Functions.toHexString(pPublicData)); //buffer.append(Constants.NEWLINE); return sb.toString(); } |
long method | Long method2 Feature envy | t | f | t | 0 | 9593 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/CK_ECDH1_DERIVE_PARAMS.java/#L107-L136 | 2 | 3795 | 9593 | minor | ||
| 1675 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setModalFieldsTooltips() { // set Tooltips this.tooltipInput.setTitle(MSGS.firewallPortForwardFormInboundInterfaceToolTip()); this.tooltipOutput.setTitle(MSGS.firewallPortForwardFormOutboundInterfaceToolTip()); this.tooltipLan.setTitle(MSGS.firewallPortForwardFormLanAddressToolTip()); this.tooltipProtocol.setTitle(MSGS.firewallPortForwardFormProtocolToolTip()); this.tooltipInternal.setTitle(MSGS.firewallPortForwardFormInternalPortToolTip()); this.tooltipExternal.setTitle(MSGS.firewallPortForwardFormExternalPortToolTip()); this.tooltipEnable.setTitle(MSGS.firewallPortForwardFormMasqueradingToolTip()); this.tooltipPermittedNw.setTitle(MSGS.firewallPortForwardFormPermittedNetworkToolTip()); this.tooltipPermittedMac.setTitle(MSGS.firewallPortForwardFormPermittedMacAddressToolTip()); this.tooltipSource.setTitle(MSGS.firewallPortForwardFormSourcePortRangeToolTip()); this.tooltipInput.reconfigure(); this.tooltipOutput.reconfigure(); this.tooltipLan.reconfigure(); this.tooltipProtocol.reconfigure(); this.tooltipExternal.reconfigure(); this.tooltipInternal.reconfigure(); this.tooltipEnable.reconfigure(); this.tooltipPermittedNw.reconfigure(); this.tooltipPermittedMac.reconfigure(); this.tooltipSource.reconfigure(); } |
long method | long method | t | t | t | 0 | 11644 | https://github.com/eclipse/kura/blob/5e9f3e3d03c8a9cc7857b3fb9080b256821bb32a/kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/firewall/PortForwardingTabUi.java/#L796-L818 | 1 | 1675 | 11644 | minor | ||
| 21 | { "answer": "YES I found bad smells", "bad smells are": "1. Long method" } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | 1. long method | t | t | t | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 21 | 682 | minor | ||
| 21 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | long method, data class | t | t | t | data class | 0 | 682 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 1 | 21 | 682 | minor | |
| 4605 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12253 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 4605 | 12253 | minor | |
| 1959 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static ClassLoader findClassLoader() throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader context = SecuritySupport.getContextClassLoader(); ClassLoader system = SecuritySupport.getSystemClassLoader(); ClassLoader chain = system; while (true) { if (context == chain) { // Assert: we are on JDK 1.1 or we have no Context ClassLoader // or any Context ClassLoader in chain of system classloader // (including extension ClassLoader) so extend to widest // ClassLoader (always look in system ClassLoader if Xalan // is in boot/extension/system classpath and in current // ClassLoader otherwise); normal classloaders delegate // back to system ClassLoader first so this widening doesn't // change the fact that context ClassLoader will be consulted ClassLoader current = ObjectFactory.class.getClassLoader(); chain = system; while (true) { if (current == chain) { // Assert: Current ClassLoader in chain of // boot/extension/system ClassLoaders return system; } if (chain == null) { break; } chain = SecuritySupport.getParentClassLoader(chain); } // Assert: Current ClassLoader not in chain of // boot/extension/system ClassLoaders return current; } if (chain == null) { // boot ClassLoader reached break; } // Check for any extension ClassLoaders in chain up to // boot ClassLoader chain = SecuritySupport.getParentClassLoader(chain); }; // Assert: Context ClassLoader not in chain of // boot/extension/system ClassLoaders return context; } // findClassLoader():ClassLoader |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12573 | https://github.com/apache/xalan-j/blob/cba6d7fe7e93defecb98d155e2a780f8a3f1fbaa/src/org/apache/xalan/xsltc/dom/ObjectFactory.java/#L391-L443 | 2 | 1959 | 12573 | minor | |
| 1543 | { "output": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public String toString() { if (subject == null || pubKey == null || interval == null || issuer == null || algId == null || serialNum == null) { throw new NullPointerException("X.509 cert is incomplete"); } StringBuilder sb = new StringBuilder(); sb.append("[\n"); sb.append(" " + version.toString() + "\n"); sb.append(" Subject: " + subject.toString() + "\n"); sb.append(" Signature Algorithm: " + algId.toString() + "\n"); sb.append(" Key: " + pubKey.toString() + "\n"); sb.append(" " + interval.toString() + "\n"); sb.append(" Issuer: " + issuer.toString() + "\n"); sb.append(" " + serialNum.toString() + "\n"); // optional v2, v3 extras if (issuerUniqueId != null) { sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); } if (subjectUniqueId != null) { sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); sb.append("\nCertificate Extensions: " + exts.length); for (int i = 0; i < exts.length; i++) { sb.append("\n[" + (i+1) + "]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { sb.append(ext.toString()); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); sb.append("Extension unknown: " + "DER encoded OCTET string =\n" + enc.encodeBuffer(extValue) + "\n"); } } else sb.append(ext.toString()); //sub-class exists } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { sb.append("\nUnparseable certificate extensions: " + invalid.size()); int i = 1; for (Extension ext : invalid.values()) { sb.append("\n[" + (i++) + "]: "); sb.append(ext); } } } sb.append("\n]"); return sb.toString(); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11243 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertInfo.java/#L292-L354 | 1 | 1543 | 11243 | critical | |
| 565 | { "output": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class FunctionExpressionNode extends RSourceSectionNode implements RSyntaxNode, RSyntaxFunction { public static FunctionExpressionNode create(SourceSection src, RootCallTarget callTarget) { return new FunctionExpressionNode(src, callTarget); } @Child private SetVisibilityNode visibility = SetVisibilityNode.create(); @CompilationFinal private RootCallTarget callTarget; private final PromiseDeoptimizeFrameNode deoptFrameNode; @CompilationFinal private boolean initialized = false; private FunctionExpressionNode(SourceSection src, RootCallTarget callTarget) { super(src); this.callTarget = callTarget; this.deoptFrameNode = EagerEvalHelper.optExprs() || EagerEvalHelper.optVars() || EagerEvalHelper.optDefault() ? new PromiseDeoptimizeFrameNode() : null; } @Override public RFunction execute(VirtualFrame frame) { visibility.execute(frame, true); MaterializedFrame matFrame = frame.materialize(); if (deoptFrameNode != null) { // Deoptimize every promise which is now in this frame, as it might leave it's stack deoptFrameNode.deoptimizeFrame(RArguments.getArguments(matFrame)); } if (!initialized) { CompilerDirectives.transferToInterpreterAndInvalidate(); if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), frame)) { if (!FrameSlotChangeMonitor.isEnclosingFrameDescriptor(callTarget.getRootNode().getFrameDescriptor(), null)) { RRootNode root = (RRootNode) callTarget.getRootNode(); callTarget = root.duplicateWithNewFrameDescriptor(); } FrameSlotChangeMonitor.initializeEnclosingFrame(callTarget.getRootNode().getFrameDescriptor(), frame); } initialized = true; } return RDataFactory.createFunction(RFunction.NO_NAME, RFunction.NO_NAME, callTarget, null, matFrame); } public RootCallTarget getCallTarget() { return callTarget; } @Override public RSyntaxElement[] getSyntaxArgumentDefaults() { return RASTUtils.asSyntaxNodes(((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getArguments()); } @Override public RSyntaxElement getSyntaxBody() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getBody(); } @Override public ArgumentsSignature getSyntaxSignature() { return ((FunctionDefinitionNode) callTarget.getRootNode()).getFormalArguments().getSignature(); } @Override public String getSyntaxDebugName() { return ((RRootNode) callTarget.getRootNode()).getName(); } } |
data class | data class, long method | t | t | t | long method | 0 | 5717 | https://github.com/oracle/fastr/blob/a1ee49060317621c0c9eceea8ec60040aca59b2d/com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/function/FunctionExpressionNode.java/#L46-L110 | 1 | 565 | 5717 | minor | |
| 772 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method, data class, feature envy | t | t | t | data class, feature envy | 0 | 7285 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 772 | 7285 | major | |
| 859 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, Feature envy | t | f | t | Feature envy | 0 | 7898 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 859 | 7898 | minor | |
| 732 | {"answer": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void tryStoreVectorizedKey(HiveKey key, boolean partColsIsNull, int batchIndex) throws HiveException, IOException { // Assumption - batchIndex is increasing; startVectorizedBatch was called int size = indexes.size(); int index = size < topN ? size : evicted; keys[index] = Arrays.copyOf(key.getBytes(), key.getLength()); distKeyLengths[index] = key.getDistKeyLength(); hashes[index] = key.hashCode(); Integer collisionIndex = indexes.store(index); if (null != collisionIndex) { /* * since there is a collision index will be used for the next value * so have the map point back to original index. */ if ( indexes instanceof HashForGroup ) { indexes.store(collisionIndex); } // forward conditional on the survival of the corresponding key currently in indexes. ++batchNumForwards; batchIndexToResult[batchIndex] = MAY_FORWARD - collisionIndex; return; } indexToBatchIndex[index] = batchIndex; batchIndexToResult[batchIndex] = index; if (size != topN) return; evicted = indexes.removeBiggest(); // remove the biggest key if (index == evicted) { excluded++; batchIndexToResult[batchIndex] = EXCLUDE; indexToBatchIndex[index] = -1; return; // input key is bigger than any of keys in hash } removed(evicted); int evictedBatchIndex = indexToBatchIndex[evicted]; if (evictedBatchIndex >= 0) { // reset the result for the evicted index batchIndexToResult[evictedBatchIndex] = EXCLUDE; indexToBatchIndex[evicted] = -1; } // Evict all results grouped with this index; it cannot be any key further in the batch. // If we evict a key from this batch, the keys grouped with it cannot be earlier that that key. // If we evict a key that is not from this batch, initial i = (-1) + 1 = 0, as intended. int evictedForward = (MAY_FORWARD - evicted); for (int i = evictedBatchIndex + 1; i < batchIndex && (batchNumForwards > 0); ++i) { if (batchIndexToResult[i] == evictedForward) { batchIndexToResult[i] = EXCLUDE; --batchNumForwards; } } } |
long method | long method | t | t | t | 0 | 6885 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/exec/TopNHash.java/#L213-L262 | 1 | 732 | 6885 | major | ||
| 791 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public LongRect getSelectionBounds(ItemSelection selection, ChartContext context) { XYItemSelection sel = (XYItemSelection)selection; XYItem item = sel.getItem(); int selectedValueIndex = sel.getValueIndex(); if (selectedValueIndex == -1 || selectedValueIndex >= item.getValuesCount()) // This happens on reset - bounds of the selection are unknown, let's clear whole area return new LongRect(0, 0, context.getViewportWidth(), context.getViewportHeight()); else return getViewBounds(item, selectedValueIndex, context); } |
long method | Long method2 Feature envy | t | f | t | 0 | 7535 | https://github.com/oracle/visualvm/blob/d9b10575b53d535e10c6e8c41831ebe38483c65b/visualvm/libs.profiler/profiler.snaptracer/src/org/graalvm/visualvm/lib/profiler/snaptracer/impl/timeline/TimelineXYPainter.java/#L145-L158 | 2 | 791 | 7535 | minor | ||
| 2042 | the bad smells are: 1. Long method 2. Duplicate code 3. Complex conditional logic 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: final protected Node internalRemoveNamedItemNS(String namespaceURI, String name, boolean raiseEx) { CoreDocumentImpl ownerDocument = ownerNode.ownerDocument(); if (ownerDocument.errorChecking && isReadOnly()) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null); throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg); } int i = findNamePoint(namespaceURI, name); if (i < 0) { if (raiseEx) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null); throw new DOMException(DOMException.NOT_FOUND_ERR, msg); } else { return null; } } AttrImpl n = (AttrImpl)nodes.get(i); if (n.isIdAttribute()) { ownerDocument.removeIdentifier(n.getValue()); } // If there's a default, add it instead String nodeName = n.getNodeName(); if (hasDefaults()) { NamedNodeMapImpl defaults = ((ElementImpl) ownerNode).getDefaultAttributes(); Node d; if (defaults != null && (d = defaults.getNamedItem(nodeName)) != null) { int j = findNamePoint(nodeName,0); if (j>=0 && findNamePoint(nodeName, j+1) < 0) { NodeImpl clone = (NodeImpl)d.cloneNode(true); clone.ownerNode = ownerNode; if (d.getLocalName() != null) { // we must rely on the name to find a default attribute // ("test:attr"), but while copying it from the DOCTYPE // we should not loose namespace URI that was assigned // to the attribute in the instance document. ((AttrNSImpl)clone).namespaceURI = namespaceURI; } clone.isOwned(true); clone.isSpecified(false); nodes.set(i, clone); if (clone.isIdAttribute()) { ownerDocument.putIdentifier(clone.getNodeValue(), (ElementImpl)ownerNode); } } else { nodes.remove(i); } } else { nodes.remove(i); } } else { nodes.remove(i); } // changed(true); // remove reference to owner n.ownerNode = ownerDocument; n.isOwned(false); // make sure it won't be mistaken with defaults in case it's // reused n.isSpecified(true); // update id table if needed n.isIdAttribute(false); // notify document ownerDocument.removedAttrNode(n, ownerNode, name); return n; } // internalRemoveNamedItemNS(String,String,boolean):Node |
long method | Long method2 Duplicate code3 Complex conditional logic4 Feature envy | f | f | t | 0 | 12854 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AttributeMap.java/#L391-L467 | 2 | 2042 | 12854 | major | ||
| 2679 | YES I found bad smells Bad smells are: 1. Long method 2. Feature envy 3. Variable name not descriptive 4. Magic number 5. Duplicated code 6. Catching broad exception types 7. Inconsistent formatting and indentation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
feature envy | Long method2 Feature envy3 Variable name not descriptive4 Magic number5 Duplicated code6 Catching broad exception types7 Inconsistent formatting and indentation | t | f | t | 0 | 15254 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 2 | 2679 | 15254 | minor | ||
| 1520 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
long method | long method | t | t | t | 0 | 11172 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 1 | 1520 | 11172 | minor | ||
| 1803 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Data class 4. Inappropriate naming 5. Inconsistent formatting and spacing 6. Deeply nested structure 7. Unused code 8. Code duplication 9. Non-optimized imports 10. Comments that are not helpful or redundant 11. Poor exception handling 12. Misplaced responsibilities 13. Overuse of static methods and variables 14. Insufficient encapsulation 15. Inconsistent use of modifiers 16. Lack of proper logging statements 17. Lack of validation for input parameters 18. Poor naming conventions for variables and methods 19. Excessive depth of inheritance hierarchy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") @Entity @Table(name = "TRIGGER", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Trigger extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer { @Override public void serialize(Trigger trigger, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", trigger.getId().toString()); jgen.writeStringField("name", trigger.getName()); jgen.writeStringField("type", trigger.getType().name()); jgen.writeNumberField("threshold", trigger.getThreshold().doubleValue()); if(trigger.getSecondaryThreshold() != null) { jgen.writeNumberField("secondaryThreshold", trigger.getSecondaryThreshold()); } if(trigger.getInertia() != null) { jgen.writeNumberField("inertia", trigger.getInertia()); } jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer { @Override public Trigger deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Trigger trigger = new Trigger(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); trigger.id = id; String name = rootNode.get("name").asText(); trigger.setName(name); TriggerType type = TriggerType.fromString(rootNode.get("type").asText()); trigger.setType(type); Double threshold = rootNode.get("threshold").asDouble(); trigger.setThreshold(threshold); if(rootNode.get("secondaryThreshold") != null) { trigger.setSecondaryThreshold(rootNode.get("secondaryThreshold").asDouble()); } if(rootNode.get("inertia") != null) { trigger.setInertia(rootNode.get("inertia").asLong()); } return trigger; } } //~ Instance fields ****************************************************************************************************************************** @Column(nullable = false) @Enumerated(EnumType.STRING) private TriggerType type; @Basic(optional = false) @Column(name = "name", nullable = false) private String name; @Basic(optional = false) private Double threshold; private Double secondaryThreshold; private Long inertia; @ManyToOne(optional = false) @JoinColumn(nullable = false, name = "alert_id") private Alert alert; @ManyToMany(mappedBy = "triggers", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private List notifications = new ArrayList<>(0); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, double threshold, long inertiaMillis) { this(alert, type, name, threshold, null, inertiaMillis); } /** * Creates a new Trigger object. * * @param alert The alert associated with the trigger. Cannot be null. * @param type The type of the alert. Cannot be null. * @param name The name of the alert. Cannot be null or empty. * @param threshold The threshold value for the alert. * @param secondaryThreshold The secondary threshold value for the alert. May be null for types that only require one threshold. * @param inertiaMillis The amount of time in milliseconds a condition must exist for the trigger to fire. Cannot be negative. */ public Trigger(Alert alert, TriggerType type, String name, Double threshold, Double secondaryThreshold, long inertiaMillis) { super(alert.getOwner()); setAlert(alert); setType(type); setName(name); setThreshold(threshold); setSecondaryThreshold(secondaryThreshold); setInertia(inertiaMillis); preUpdate(); } /** Creates a new Trigger object. */ protected Trigger() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Evaluates the trigger against actualValue (passed as parameter). * * @param trigger trigger to be evaluated. * @param actualValue value against the trigger to be evaluated. * * @return true if the trigger should be fired so that notification will be sent otherwise false. * * @throws SystemException If an error in evaluation occurs. */ public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } } //~ Methods ************************************************************************************************************************************** /** * Returns the notifications associated with the trigger. * * @return The associated notifications. */ public List getNotifications() { return Collections.unmodifiableList(notifications); } /** * Returns the trigger type. * * @return The trigger type. Will never be null. */ public TriggerType getType() { return type; } /** * Sets the trigger type. * * @param type The trigger type. Cannot be null. */ public void setType(TriggerType type) { requireArgument(type != null, "The trigger type cannot be null."); this.type = type; } /** * Returns the trigger name. * * @return The trigger name. Will never be null. */ public String getName() { return name; } /** * Sets the name of the trigger. * * @param name The trigger name. Cannot be null or empty. */ public void setName(String name) { requireArgument(name != null && !name.isEmpty(), "Trigger name cannot be null or empty."); this.name = name; } /** * Returns the trigger threshold. * * @return The trigger threshold. */ public Double getThreshold() { return threshold; } /** * Sets the trigger threshold. * * @param threshold The trigger threshold. Cannot be null. */ public void setThreshold(Double threshold) { requireArgument(threshold != null, "Trigger threshold cannot be null."); this.threshold = threshold; } /** * Returns the secondary threshold for the trigger. * * @return The secondary threshold. Can return null for trigger types that only require a single threshold. */ public Double getSecondaryThreshold() { return secondaryThreshold; } /** * Sets the secondary threshold for the trigger. * * @param secondaryThreshold The secondary threshold. Can be null for trigger types that only require a single threshold. */ public void setSecondaryThreshold(Double secondaryThreshold) { this.secondaryThreshold = secondaryThreshold; } /** * Returns the inertia associated with the trigger in milliseconds. * * @return The inertia in milliseconds. */ public Long getInertia() { return inertia; } /** * Sets the inertia associated with the trigger in milliseconds. * * @param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. */ public void setInertia(Long inertiaMillis) { if (this.alert == null) { // Only during deserialization. this.inertia = inertiaMillis; } else { requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative."); Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression()); if (inertiaMillis > longestIntervalLength) throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength)); this.inertia = inertiaMillis; } } /** * Returns the alert with which the trigger is associated. * * @return The alert with which the trigger is associated. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the trigger is associated. * * @param alert The alert with which the trigger is associated. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which a trigger is associated cannot be null."); this.alert = alert; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Trigger other = (Trigger) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { if (type == TriggerType.BETWEEN || type == TriggerType.NOT_BETWEEN) return "Trigger{" + "type=" + type + ", name=" + name + ", primaryThreshold=" + threshold + ", secondaryThreshold=" + secondaryThreshold + ", inertia=" + inertia + '}'; else return "Trigger{" + "type=" + type + ", name=" + name + ", threshold=" + threshold + ", inertia=" + inertia + '}'; } //~ Enums **************************************************************************************************************************************** /** * The type of trigger. * * @author Tom Valine (tvaline@salesforce.com) */ public enum TriggerType { /** Greater than. */ GREATER_THAN, /** Greater than or equal to. */ GREATER_THAN_OR_EQ, /** Less than. */ LESS_THAN, /** Less than or equal to. */ LESS_THAN_OR_EQ, /** Equal to. */ EQUAL, /** Not equal to. */ NOT_EQUAL, /** Between. */ BETWEEN, /** Not between. */ NOT_BETWEEN, /** No Data */ NO_DATA; /** * Converts a string to a trigger type. * * @param name The trigger type name. * * @return The corresponding trigger type. * * @throws IllegalArgumentException If no corresponding trigger type is found. */ @JsonCreator public static TriggerType fromString(String name) { for (TriggerType t : TriggerType.values()) { if (t.toString().equalsIgnoreCase(name)) { return t; } } throw new IllegalArgumentException("Trigger Type does not exist."); } /** * Returns the name of the trigger type. * * @return The name of the trigger type. */ @JsonValue public String value() { return this.toString(); } } } |
data class | Long method2 Feature envy3 Data class4 Inappropriate naming5 Inconsistent formatting and spacing6 Deeply nested structure7 Unused code8 Code duplication9 Non-optimized imports | t | f | t | 0 | 12021 | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java/#L88-L491 | 2 | 1803 | 12021 | major | ||
| 1125 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10003 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 1125 | 10003 | minor | |
| 2359 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14234 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 2359 | 14234 | minor | |
| 982 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Component getNextComponent(final Container container, final Component component, final FocusTraversalDirection direction) { Utils.checkNull(container, "container"); Utils.checkNull(direction, "direction"); Component nextComponent = null; int n = container.getLength(); if (n > 0) { switch (direction) { case FORWARD: if (component == null) { // Return the first component in the sequence nextComponent = container.get(0); } else { // Return the next component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index < n - 1) { nextComponent = container.get(index + 1); } else { if (wrap) { nextComponent = container.get(0); } } } break; case BACKWARD: if (component == null) { // Return the last component in the sequence nextComponent = container.get(n - 1); } else { // Return the previous component in the sequence int index = container.indexOf(component); if (index == -1) { throw new IllegalArgumentException("Component is not a child of the container."); } if (index > 0) { nextComponent = container.get(index - 1); } else { if (wrap) { nextComponent = container.get(n - 1); } } } break; default: break; } } return nextComponent; } |
long method | long method | t | t | t | 0 | 8859 | https://github.com/apache/pivot/blob/568543f3396648a646341fe077a714eb06d556c0/wtk/src/org/apache/pivot/wtk/skin/ContainerSkin.java/#L57-L118 | 1 | 982 | 8859 | major | ||
| 1531 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class APIRequestGet extends APIRequest { AdCampaignActivity lastResponse = null; @Override public AdCampaignActivity getLastResponse() { return lastResponse; } public static final String[] PARAMS = { }; public static final String[] FIELDS = { "auto_create_lookalike_new", "auto_create_lookalike_old", "bid_adjustments_spec_new", "bid_adjustments_spec_old", "bid_amount_new", "bid_amount_old", "bid_constraints_new", "bid_constraints_old", "bid_info_new", "bid_info_old", "bid_strategy_new", "bid_strategy_old", "bid_type_new", "bid_type_old", "billing_event_new", "billing_event_old", "brande_audience_id_new", "brande_audience_id_old", "budget_limit_new", "budget_limit_old", "created_time", "daily_impressions_new", "daily_impressions_old", "dco_mode_new", "dco_mode_old", "delivery_behavior_new", "delivery_behavior_old", "destination_type_new", "destination_type_old", "event_time", "event_type", "id", "invoicing_limit_new", "invoicing_limit_old", "min_spend_target_new", "min_spend_target_old", "name_new", "name_old", "optimization_goal_new", "optimization_goal_old", "pacing_type_new", "pacing_type_old", "run_status_new", "run_status_old", "schedule_new", "schedule_old", "spend_cap_new", "spend_cap_old", "start_time_new", "start_time_old", "stop_time_new", "stop_time_old", "targeting_expansion_new", "targeting_expansion_old", "updated_time_new", "updated_time_old", }; @Override public AdCampaignActivity parseResponse(String response, String header) throws APIException { return AdCampaignActivity.parseResponse(response, getContext(), this, header).head(); } @Override public AdCampaignActivity execute() throws APIException { return execute(new HashMap()); } @Override public AdCampaignActivity execute(Map extraParams) throws APIException { ResponseWrapper rw = executeInternal(extraParams); lastResponse = parseResponse(rw.getBody(), rw.getHeader()); return lastResponse; } public ListenableFuture executeAsync() throws APIException { return executeAsync(new HashMap()); }; public ListenableFuture executeAsync(Map extraParams) throws APIException { return Futures.transform( executeAsyncInternal(extraParams), new Function() { public AdCampaignActivity apply(ResponseWrapper result) { try { return APIRequestGet.this.parseResponse(result.getBody(), result.getHeader()); } catch (Exception e) { throw new RuntimeException(e); } } } ); }; public APIRequestGet(String nodeId, APIContext context) { super(context, nodeId, "/", "GET", Arrays.asList(PARAMS)); } @Override public APIRequestGet setParam(String param, Object value) { setParamInternal(param, value); return this; } @Override public APIRequestGet setParams(Map params) { setParamsInternal(params); return this; } public APIRequestGet requestAllFields () { return this.requestAllFields(true); } public APIRequestGet requestAllFields (boolean value) { for (String field : FIELDS) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestFields (List fields) { return this.requestFields(fields, true); } @Override public APIRequestGet requestFields (List fields, boolean value) { for (String field : fields) { this.requestField(field, value); } return this; } @Override public APIRequestGet requestField (String field) { this.requestField(field, true); return this; } @Override public APIRequestGet requestField (String field, boolean value) { this.requestFieldInternal(field, value); return this; } public APIRequestGet requestAutoCreateLookalikeNewField () { return this.requestAutoCreateLookalikeNewField(true); } public APIRequestGet requestAutoCreateLookalikeNewField (boolean value) { this.requestField("auto_create_lookalike_new", value); return this; } public APIRequestGet requestAutoCreateLookalikeOldField () { return this.requestAutoCreateLookalikeOldField(true); } public APIRequestGet requestAutoCreateLookalikeOldField (boolean value) { this.requestField("auto_create_lookalike_old", value); return this; } public APIRequestGet requestBidAdjustmentsSpecNewField () { return this.requestBidAdjustmentsSpecNewField(true); } public APIRequestGet requestBidAdjustmentsSpecNewField (boolean value) { this.requestField("bid_adjustments_spec_new", value); return this; } public APIRequestGet requestBidAdjustmentsSpecOldField () { return this.requestBidAdjustmentsSpecOldField(true); } public APIRequestGet requestBidAdjustmentsSpecOldField (boolean value) { this.requestField("bid_adjustments_spec_old", value); return this; } public APIRequestGet requestBidAmountNewField () { return this.requestBidAmountNewField(true); } public APIRequestGet requestBidAmountNewField (boolean value) { this.requestField("bid_amount_new", value); return this; } public APIRequestGet requestBidAmountOldField () { return this.requestBidAmountOldField(true); } public APIRequestGet requestBidAmountOldField (boolean value) { this.requestField("bid_amount_old", value); return this; } public APIRequestGet requestBidConstraintsNewField () { return this.requestBidConstraintsNewField(true); } public APIRequestGet requestBidConstraintsNewField (boolean value) { this.requestField("bid_constraints_new", value); return this; } public APIRequestGet requestBidConstraintsOldField () { return this.requestBidConstraintsOldField(true); } public APIRequestGet requestBidConstraintsOldField (boolean value) { this.requestField("bid_constraints_old", value); return this; } public APIRequestGet requestBidInfoNewField () { return this.requestBidInfoNewField(true); } public APIRequestGet requestBidInfoNewField (boolean value) { this.requestField("bid_info_new", value); return this; } public APIRequestGet requestBidInfoOldField () { return this.requestBidInfoOldField(true); } public APIRequestGet requestBidInfoOldField (boolean value) { this.requestField("bid_info_old", value); return this; } public APIRequestGet requestBidStrategyNewField () { return this.requestBidStrategyNewField(true); } public APIRequestGet requestBidStrategyNewField (boolean value) { this.requestField("bid_strategy_new", value); return this; } public APIRequestGet requestBidStrategyOldField () { return this.requestBidStrategyOldField(true); } public APIRequestGet requestBidStrategyOldField (boolean value) { this.requestField("bid_strategy_old", value); return this; } public APIRequestGet requestBidTypeNewField () { return this.requestBidTypeNewField(true); } public APIRequestGet requestBidTypeNewField (boolean value) { this.requestField("bid_type_new", value); return this; } public APIRequestGet requestBidTypeOldField () { return this.requestBidTypeOldField(true); } public APIRequestGet requestBidTypeOldField (boolean value) { this.requestField("bid_type_old", value); return this; } public APIRequestGet requestBillingEventNewField () { return this.requestBillingEventNewField(true); } public APIRequestGet requestBillingEventNewField (boolean value) { this.requestField("billing_event_new", value); return this; } public APIRequestGet requestBillingEventOldField () { return this.requestBillingEventOldField(true); } public APIRequestGet requestBillingEventOldField (boolean value) { this.requestField("billing_event_old", value); return this; } public APIRequestGet requestBrandeAudienceIdNewField () { return this.requestBrandeAudienceIdNewField(true); } public APIRequestGet requestBrandeAudienceIdNewField (boolean value) { this.requestField("brande_audience_id_new", value); return this; } public APIRequestGet requestBrandeAudienceIdOldField () { return this.requestBrandeAudienceIdOldField(true); } public APIRequestGet requestBrandeAudienceIdOldField (boolean value) { this.requestField("brande_audience_id_old", value); return this; } public APIRequestGet requestBudgetLimitNewField () { return this.requestBudgetLimitNewField(true); } public APIRequestGet requestBudgetLimitNewField (boolean value) { this.requestField("budget_limit_new", value); return this; } public APIRequestGet requestBudgetLimitOldField () { return this.requestBudgetLimitOldField(true); } public APIRequestGet requestBudgetLimitOldField (boolean value) { this.requestField("budget_limit_old", value); return this; } public APIRequestGet requestCreatedTimeField () { return this.requestCreatedTimeField(true); } public APIRequestGet requestCreatedTimeField (boolean value) { this.requestField("created_time", value); return this; } public APIRequestGet requestDailyImpressionsNewField () { return this.requestDailyImpressionsNewField(true); } public APIRequestGet requestDailyImpressionsNewField (boolean value) { this.requestField("daily_impressions_new", value); return this; } public APIRequestGet requestDailyImpressionsOldField () { return this.requestDailyImpressionsOldField(true); } public APIRequestGet requestDailyImpressionsOldField (boolean value) { this.requestField("daily_impressions_old", value); return this; } public APIRequestGet requestDcoModeNewField () { return this.requestDcoModeNewField(true); } public APIRequestGet requestDcoModeNewField (boolean value) { this.requestField("dco_mode_new", value); return this; } public APIRequestGet requestDcoModeOldField () { return this.requestDcoModeOldField(true); } public APIRequestGet requestDcoModeOldField (boolean value) { this.requestField("dco_mode_old", value); return this; } public APIRequestGet requestDeliveryBehaviorNewField () { return this.requestDeliveryBehaviorNewField(true); } public APIRequestGet requestDeliveryBehaviorNewField (boolean value) { this.requestField("delivery_behavior_new", value); return this; } public APIRequestGet requestDeliveryBehaviorOldField () { return this.requestDeliveryBehaviorOldField(true); } public APIRequestGet requestDeliveryBehaviorOldField (boolean value) { this.requestField("delivery_behavior_old", value); return this; } public APIRequestGet requestDestinationTypeNewField () { return this.requestDestinationTypeNewField(true); } public APIRequestGet requestDestinationTypeNewField (boolean value) { this.requestField("destination_type_new", value); return this; } public APIRequestGet requestDestinationTypeOldField () { return this.requestDestinationTypeOldField(true); } public APIRequestGet requestDestinationTypeOldField (boolean value) { this.requestField("destination_type_old", value); return this; } public APIRequestGet requestEventTimeField () { return this.requestEventTimeField(true); } public APIRequestGet requestEventTimeField (boolean value) { this.requestField("event_time", value); return this; } public APIRequestGet requestEventTypeField () { return this.requestEventTypeField(true); } public APIRequestGet requestEventTypeField (boolean value) { this.requestField("event_type", value); return this; } public APIRequestGet requestIdField () { return this.requestIdField(true); } public APIRequestGet requestIdField (boolean value) { this.requestField("id", value); return this; } public APIRequestGet requestInvoicingLimitNewField () { return this.requestInvoicingLimitNewField(true); } public APIRequestGet requestInvoicingLimitNewField (boolean value) { this.requestField("invoicing_limit_new", value); return this; } public APIRequestGet requestInvoicingLimitOldField () { return this.requestInvoicingLimitOldField(true); } public APIRequestGet requestInvoicingLimitOldField (boolean value) { this.requestField("invoicing_limit_old", value); return this; } public APIRequestGet requestMinSpendTargetNewField () { return this.requestMinSpendTargetNewField(true); } public APIRequestGet requestMinSpendTargetNewField (boolean value) { this.requestField("min_spend_target_new", value); return this; } public APIRequestGet requestMinSpendTargetOldField () { return this.requestMinSpendTargetOldField(true); } public APIRequestGet requestMinSpendTargetOldField (boolean value) { this.requestField("min_spend_target_old", value); return this; } public APIRequestGet requestNameNewField () { return this.requestNameNewField(true); } public APIRequestGet requestNameNewField (boolean value) { this.requestField("name_new", value); return this; } public APIRequestGet requestNameOldField () { return this.requestNameOldField(true); } public APIRequestGet requestNameOldField (boolean value) { this.requestField("name_old", value); return this; } public APIRequestGet requestOptimizationGoalNewField () { return this.requestOptimizationGoalNewField(true); } public APIRequestGet requestOptimizationGoalNewField (boolean value) { this.requestField("optimization_goal_new", value); return this; } public APIRequestGet requestOptimizationGoalOldField () { return this.requestOptimizationGoalOldField(true); } public APIRequestGet requestOptimizationGoalOldField (boolean value) { this.requestField("optimization_goal_old", value); return this; } public APIRequestGet requestPacingTypeNewField () { return this.requestPacingTypeNewField(true); } public APIRequestGet requestPacingTypeNewField (boolean value) { this.requestField("pacing_type_new", value); return this; } public APIRequestGet requestPacingTypeOldField () { return this.requestPacingTypeOldField(true); } public APIRequestGet requestPacingTypeOldField (boolean value) { this.requestField("pacing_type_old", value); return this; } public APIRequestGet requestRunStatusNewField () { return this.requestRunStatusNewField(true); } public APIRequestGet requestRunStatusNewField (boolean value) { this.requestField("run_status_new", value); return this; } public APIRequestGet requestRunStatusOldField () { return this.requestRunStatusOldField(true); } public APIRequestGet requestRunStatusOldField (boolean value) { this.requestField("run_status_old", value); return this; } public APIRequestGet requestScheduleNewField () { return this.requestScheduleNewField(true); } public APIRequestGet requestScheduleNewField (boolean value) { this.requestField("schedule_new", value); return this; } public APIRequestGet requestScheduleOldField () { return this.requestScheduleOldField(true); } public APIRequestGet requestScheduleOldField (boolean value) { this.requestField("schedule_old", value); return this; } public APIRequestGet requestSpendCapNewField () { return this.requestSpendCapNewField(true); } public APIRequestGet requestSpendCapNewField (boolean value) { this.requestField("spend_cap_new", value); return this; } public APIRequestGet requestSpendCapOldField () { return this.requestSpendCapOldField(true); } public APIRequestGet requestSpendCapOldField (boolean value) { this.requestField("spend_cap_old", value); return this; } public APIRequestGet requestStartTimeNewField () { return this.requestStartTimeNewField(true); } public APIRequestGet requestStartTimeNewField (boolean value) { this.requestField("start_time_new", value); return this; } public APIRequestGet requestStartTimeOldField () { return this.requestStartTimeOldField(true); } public APIRequestGet requestStartTimeOldField (boolean value) { this.requestField("start_time_old", value); return this; } public APIRequestGet requestStopTimeNewField () { return this.requestStopTimeNewField(true); } public APIRequestGet requestStopTimeNewField (boolean value) { this.requestField("stop_time_new", value); return this; } public APIRequestGet requestStopTimeOldField () { return this.requestStopTimeOldField(true); } public APIRequestGet requestStopTimeOldField (boolean value) { this.requestField("stop_time_old", value); return this; } public APIRequestGet requestTargetingExpansionNewField () { return this.requestTargetingExpansionNewField(true); } public APIRequestGet requestTargetingExpansionNewField (boolean value) { this.requestField("targeting_expansion_new", value); return this; } public APIRequestGet requestTargetingExpansionOldField () { return this.requestTargetingExpansionOldField(true); } public APIRequestGet requestTargetingExpansionOldField (boolean value) { this.requestField("targeting_expansion_old", value); return this; } public APIRequestGet requestUpdatedTimeNewField () { return this.requestUpdatedTimeNewField(true); } public APIRequestGet requestUpdatedTimeNewField (boolean value) { this.requestField("updated_time_new", value); return this; } public APIRequestGet requestUpdatedTimeOldField () { return this.requestUpdatedTimeOldField(true); } public APIRequestGet requestUpdatedTimeOldField (boolean value) { this.requestField("updated_time_old", value); return this; } } |
blob | blob, data class, long method | t | t | t | data class, long method | 0 | 11208 | https://github.com/facebook/facebook-java-business-sdk/blob/561f1a75e1220b55a160a1b92b0187f72be9cd08/src/main/java/com/facebook/ads/sdk/AdCampaignActivity.java/#L610-L1160 | 1 | 1531 | 11208 | critical | |
| 1475 | { "output": "YES I found bad smells", "detected_bad_smells": { "the bad smells are": [ "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | the bad smells are: data class | t | t | f | data class | 0 | 11062 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 1475 | 11062 | major | |
| 2508 | {"message": "YES I found bad smells", "smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1953 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1953() {} public Customer1953(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1953[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 14675 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1953.java/#L8-L27 | 1 | 2508 | 14675 | minor | ||
| 545 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Repeated code (oatMagicAndVersion) 4. Magic numbers (4, 3, 12) 5. Code duplication in the switch statement (result assignment) 6. Nested try/catch statements 7. Exception handling within a finally block 8. Multiple exit points in the method (return statement within the switch statement) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getOatFileInstructionSet(File oatFile) throws Throwable { ShareElfFile elfFile = null; String result = ""; try { elfFile = new ShareElfFile(oatFile); final ShareElfFile.SectionHeader roDataHdr = elfFile.getSectionHeaderByName(".rodata"); if (roDataHdr == null) { throw new IOException("Unable to find .rodata section."); } final FileChannel channel = elfFile.getChannel(); channel.position(roDataHdr.shOffset); final byte[] oatMagicAndVersion = new byte[8]; ShareElfFile.readUntilLimit(channel, ByteBuffer.wrap(oatMagicAndVersion), "Failed to read oat magic and version."); if (oatMagicAndVersion[0] != 'o' || oatMagicAndVersion[1] != 'a' || oatMagicAndVersion[2] != 't' || oatMagicAndVersion[3] != '\n') { throw new IOException( String.format("Bad oat magic: %x %x %x %x", oatMagicAndVersion[0], oatMagicAndVersion[1], oatMagicAndVersion[2], oatMagicAndVersion[3]) ); } final int versionOffsetFromOatBegin = 4; final int versionBytes = 3; final String oatVersion = new String(oatMagicAndVersion, versionOffsetFromOatBegin, versionBytes, Charset.forName("ASCII")); try { Integer.parseInt(oatVersion); } catch (NumberFormatException e) { throw new IOException("Bad oat version: " + oatVersion); } ByteBuffer buffer = ByteBuffer.allocate(128); buffer.order(elfFile.getDataOrder()); // TODO This is a risk point, since each oat version may use a different offset. // So far it's ok. Perhaps we should use oatVersionNum to judge the right offset in // the future. final int isaNumOffsetFromOatBegin = 12; channel.position(roDataHdr.shOffset + isaNumOffsetFromOatBegin); buffer.limit(4); ShareElfFile.readUntilLimit(channel, buffer, "Failed to read isa num."); int isaNum = buffer.getInt(); if (isaNum < 0 || isaNum >= InstructionSet.values().length) { throw new IOException("Bad isa num: " + isaNum); } switch (InstructionSet.values()[isaNum]) { case kArm: case kThumb2: result = "arm"; break; case kArm64: result = "arm64"; break; case kX86: result = "x86"; break; case kX86_64: result = "x86_64"; break; case kMips: result = "mips"; break; case kMips64: result = "mips64"; break; case kNone: result = "none"; break; default: throw new IOException("Should not reach here."); } } finally { if (elfFile != null) { try { elfFile.close(); } catch (Exception ignored) { // Ignored. } } } return result; } |
feature envy | Long method2 Feature envy3 Repeated code (oatMagicAndVersion)4 Magic numbers (4, 3, | t | f | t | 3, | 0 | 5547 | https://github.com/Tencent/tinker/blob/7523900600317ebd618f3505434176b381bd0bc2/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/shareutil/ShareOatUtil.java/#L48-L139 | 2 | 545 | 5547 | minor | |
| 103 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Event { final Type type; final TruffleFile file; final IOException ioe; final BasicFileAttributes attrs; Event(Type type, TruffleFile file, BasicFileAttributes attrs) { this.type = type; this.file = file; this.attrs = attrs; this.ioe = null; } Event(Type type, TruffleFile file, IOException ioe) { this.type = type; this.file = file; this.attrs = null; this.ioe = ioe; } enum Type { PRE_VISIT_DIRECTORY, VISIT, POST_VISIT_DIRECTORY } } |
data class | data class, long method | t | t | t | long method | 0 | 1357 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/truffle/src/com.oracle.truffle.api/src/com/oracle/truffle/api/TruffleFile.java/#L1837-L1863 | 1 | 103 | 1357 | minor | |
| 5531 | YES, I found bad smells the bad smells are: 1. Long method 2. Data class | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | Long method2 Data class | t | f | t | 0 | 5816 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 1 | 5531 | 5816 | minor | ||
| 2433 | {"response": "YES I found bad smells", "the bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject NetworkExternalLoadBalancerDao _networkExternalLBDao; @Inject ExternalLoadBalancerDeviceDao _externalLoadBalancerDeviceDao; @Inject HostDao _hostDao; @Inject DataCenterDao _dcDao; @Inject NetworkModel _networkModel; @Inject NetworkOrchestrationService _networkMgr; @Inject InlineLoadBalancerNicMapDao _inlineLoadBalancerNicMapDao; @Inject NicDao _nicDao; @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject IPAddressDao _ipAddressDao; @Inject VlanDao _vlanDao; @Inject NetworkOfferingDao _networkOfferingDao; @Inject AccountDao _accountDao; @Inject PhysicalNetworkDao _physicalNetworkDao; @Inject PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @Inject AccountManager _accountMgr; @Inject UserStatisticsDao _userStatsDao; @Inject NetworkDao _networkDao; @Inject DomainRouterDao _routerDao; @Inject LoadBalancerDao _loadBalancerDao; @Inject PortForwardingRulesDao _portForwardingRulesDao; @Inject ConfigurationDao _configDao; @Inject HostDetailsDao _hostDetailDao; @Inject NetworkExternalLoadBalancerDao _networkLBDao; @Inject NetworkServiceMapDao _ntwkSrvcProviderDao; @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject ExternalFirewallDeviceDao _externalFirewallDeviceDao; @Inject protected HostPodDao _podDao = null; @Inject IpAddressManager _ipAddrMgr; @Inject protected VirtualMachineManager _itMgr; @Inject VMInstanceDao _vmDao; @Inject VMTemplateDao _templateDao; @Inject ServiceOfferingDao _serviceOfferingDao; @Inject PhysicalNetworkServiceProviderDao _physicalProviderDao; @Inject VirtualRouterProviderDao _vrProviderDao; private long _defaultLbCapacity; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); @Override @DB public ExternalLoadBalancerDeviceVO addExternalLoadBalancer(long physicalNetworkId, String url, String username, String password, final String deviceName, ServerResource resource, final boolean gslbProvider, final boolean exclusiveGslbProivider, final String gslbSitePublicIp, final String gslbSitePrivateIp) { PhysicalNetworkVO pNetwork = null; final NetworkDevice ntwkDevice = NetworkDevice.getNetworkDevice(deviceName); long zoneId; if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + " server resource, zone id/physical network id) is not specified or a valid parameter."); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } zoneId = pNetwork.getDataCenterId(); PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); } if (gslbProvider) { ExternalLoadBalancerDeviceVO zoneGslbProvider = _externalLoadBalancerDeviceDao.findGslbServiceProvider(physicalNetworkId, ntwkDevice.getNetworkServiceProvder()); if (zoneGslbProvider != null) { throw new CloudRuntimeException("There is a GSLB service provider configured in the zone alredy."); } } URI uri; try { uri = new URI(url); } catch (Exception e) { s_logger.debug(e); throw new InvalidParameterValueException(e.getMessage()); } String ipAddress = uri.getHost(); Map hostDetails = new HashMap(); String hostName = getExternalLoadBalancerResourceGuid(pNetwork.getId(), deviceName, ipAddress); hostDetails.put("name", hostName); hostDetails.put("guid", UUID.randomUUID().toString()); hostDetails.put("zoneId", String.valueOf(pNetwork.getDataCenterId())); hostDetails.put("ip", ipAddress); hostDetails.put("physicalNetworkId", String.valueOf(pNetwork.getId())); hostDetails.put("username", username); hostDetails.put("password", password); hostDetails.put("deviceName", deviceName); // leave parameter validation to be part server resource configure Map configParams = new HashMap(); UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams); hostDetails.putAll(configParams); try { resource.configure(hostName, hostDetails); final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalLoadBalancer, hostDetails); if (host != null) { final boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } final long capacityFinal = capacity; final PhysicalNetworkVO pNetworkFinal = pNetwork; return Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetworkFinal.getId(), ntwkDevice.getNetworkServiceProvder(), deviceName, capacityFinal, dedicatedUse, gslbProvider); if (gslbProvider) { lbDeviceVO.setGslbSitePublicIP(gslbSitePublicIp); lbDeviceVO.setGslbSitePrivateIP(gslbSitePrivateIp); lbDeviceVO.setExclusiveGslbProvider(exclusiveGslbProivider); } _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); _hostDetailDao.persist(hostDetail); return lbDeviceVO; } }); } else { throw new CloudRuntimeException("Failed to add load balancer device due to internal error."); } } catch (ConfigurationException e) { throw new CloudRuntimeException(e.getMessage()); } } @Override public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); long lbDeviceId = Long.parseLong(lbHostDetails.getValue()); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); if (lbDeviceVo.getAllocationState() == LBDeviceAllocationState.Provider) { // check if cloudstack has provisioned any load balancer appliance on the device before deleting List lbDevices = _externalLoadBalancerDeviceDao.listAll(); if (lbDevices != null) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getParentHostId() == hostId) { throw new CloudRuntimeException( "This load balancer device can not be deleted as there are one or more load balancers applainces provisioned by cloudstack on the device."); } } } } else { // check if any networks are using this load balancer device List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); if ((networks != null) && !networks.isEmpty()) { throw new CloudRuntimeException("Delete can not be done as there are networks using this load balancer device "); } } try { // put the host in maintenance state in order for it to be deleted externalLoadBalancer.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, externalLoadBalancer); _resourceMgr.deleteHost(hostId, false, false); // delete the external load balancer entry _externalLoadBalancerDeviceDao.remove(lbDeviceId); return true; } catch (Exception e) { s_logger.debug(e); return false; } } @Override public List listExternalLoadBalancers(long physicalNetworkId, String deviceName) { List lbHosts = new ArrayList(); NetworkDevice lbNetworkDevice = NetworkDevice.getNetworkDevice(deviceName); PhysicalNetworkVO pNetwork = null; pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), lbNetworkDevice.getNetworkServiceProvder()); // if provider not configured in to physical network, then there can be no instances if (ntwkSvcProvider == null) { return null; } List lbDevices = _externalLoadBalancerDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); for (ExternalLoadBalancerDeviceVO provderInstance : lbDevices) { lbHosts.add(_hostDao.findById(provderInstance.getHostId())); } return lbHosts; } public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setNumRetries(lbDetails.get("numRetries")); return response; } public String getExternalLoadBalancerResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @Override public ExternalLoadBalancerDeviceVO getExternalLoadBalancerForNetwork(Network network) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = _networkExternalLBDao.findByNetworkId(network.getId()); if (lbDeviceForNetwork != null) { long lbDeviceId = lbDeviceForNetwork.getExternalLBDeviceId(); ExternalLoadBalancerDeviceVO lbDeviceVo = _externalLoadBalancerDeviceDao.findById(lbDeviceId); assert (lbDeviceVo != null); return lbDeviceVo; } return null; } public void setExternalLoadBalancerForNetwork(Network network, long externalLBDeviceID) { NetworkExternalLoadBalancerVO lbDeviceForNetwork = new NetworkExternalLoadBalancerVO(network.getId(), externalLBDeviceID); _networkExternalLBDao.persist(lbDeviceForNetwork); } @DB protected ExternalLoadBalancerDeviceVO allocateLoadBalancerForNetwork(final Network guestConfig) throws InsufficientCapacityException { boolean retry = true; boolean tryLbProvisioning = false; ExternalLoadBalancerDeviceVO lbDevice = null; long physicalNetworkId = guestConfig.getPhysicalNetworkId(); NetworkOfferingVO offering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId()); String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(guestConfig.getId(), Service.Lb); while (retry) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { try { final boolean dedicatedLB = offering.isDedicatedLB(); // does network offering supports a dedicated load balancer? try { lbDevice = Transaction.execute(new TransactionCallbackWithException() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { // FIXME: should the device allocation be done during network implement phase or do a // lazy allocation when first rule for the network is configured?? // find a load balancer device for this network as per the network offering ExternalLoadBalancerDeviceVO lbDevice = findSuitableLoadBalancerForNetwork(guestConfig, dedicatedLB); long lbDeviceId = lbDevice.getId(); // persist the load balancer device id that will be used for this network. Once a network // is implemented on a LB device then later on all rules will be programmed on to same device NetworkExternalLoadBalancerVO networkLB = new NetworkExternalLoadBalancerVO(guestConfig.getId(), lbDeviceId); _networkExternalLBDao.persist(networkLB); // mark device to be either dedicated or shared use lbDevice.setAllocationState(dedicatedLB ? LBDeviceAllocationState.Dedicated : LBDeviceAllocationState.Shared); _externalLoadBalancerDeviceDao.update(lbDeviceId, lbDevice); return lbDevice; } }); // allocated load balancer for the network, so skip retry tryLbProvisioning = false; retry = false; } catch (InsufficientCapacityException exception) { // if already attempted to provision load balancer then throw out of capacity exception, if (tryLbProvisioning) { retry = false; // TODO: throwing warning instead of error for now as its possible another provider can service this network s_logger.warn("There are no load balancer device with the capacity for implementing this network"); throw exception; } else { tryLbProvisioning = true; // if possible provision a LB appliance in to the physical network } } } finally { deviceMapLock.unlock(); } } } finally { deviceMapLock.releaseRef(); } // there are no LB devices or there is no free capacity on the devices in the physical network so provision a new LB appliance if (tryLbProvisioning) { // check if LB appliance can be dynamically provisioned List providerLbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Provider); if ((providerLbDevices != null) && (!providerLbDevices.isEmpty())) { for (ExternalLoadBalancerDeviceVO lbProviderDevice : providerLbDevices) { if (lbProviderDevice.getState() == LBDeviceState.Enabled) { // acquire a private IP from the data center which will be used as management IP of provisioned LB appliance, DataCenterIpAddressVO dcPrivateIp = _dcDao.allocatePrivateIpAddress(guestConfig.getDataCenterId(), lbProviderDevice.getUuid()); if (dcPrivateIp == null) { throw new InsufficientNetworkCapacityException("failed to acquire a priavate IP in the zone " + guestConfig.getDataCenterId() + " needed for management IP of the load balancer appliance", DataCenter.class, guestConfig.getDataCenterId()); } Pod pod = _podDao.findById(dcPrivateIp.getPodId()); String lbIP = dcPrivateIp.getIpAddress(); String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); String gateway = pod.getGateway(); // send CreateLoadBalancerApplianceCommand to the host capable of provisioning CreateLoadBalancerApplianceCommand lbProvisionCmd = new CreateLoadBalancerApplianceCommand(lbIP, netmask, gateway); CreateLoadBalancerApplianceAnswer createLbAnswer = null; try { createLbAnswer = (CreateLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbProvisionCmd); if (createLbAnswer == null || !createLbAnswer.getResult()) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId()); continue; } } catch (Exception agentException) { s_logger.error("Could not provision load balancer instance on the load balancer device " + lbProviderDevice.getId() + " due to " + agentException.getMessage()); continue; } String username = createLbAnswer.getUsername(); String password = createLbAnswer.getPassword(); String publicIf = createLbAnswer.getPublicInterface(); String privateIf = createLbAnswer.getPrivateInterface(); // we have provisioned load balancer so add the appliance as cloudstack provisioned external load balancer String dedicatedLb = offering.isDedicatedLB() ? "true" : "false"; String capacity = Long.toString(lbProviderDevice.getCapacity()); // acquire a public IP to associate with lb appliance (used as subnet IP to make the appliance part of private network) PublicIp publicIp = _ipAddrMgr.assignPublicIpAddress(guestConfig.getDataCenterId(), null, _accountMgr.getSystemAccount(), VlanType.VirtualNetwork, null, null, false, false); String publicIPNetmask = publicIp.getVlanNetmask(); String publicIPgateway = publicIp.getVlanGateway(); String publicIP = publicIp.getAddress().toString(); String publicIPVlanTag=""; try { publicIPVlanTag = BroadcastDomainType.getValue(publicIp.getVlanTag()); } catch (URISyntaxException e) { s_logger.error("Failed to parse public ip vlan tag" + e.getMessage()); } String url = "https://" + lbIP + "?publicinterface=" + publicIf + "&privateinterface=" + privateIf + "&lbdevicededicated=" + dedicatedLb + "&cloudmanaged=true" + "&publicip=" + publicIP + "&publicipnetmask=" + publicIPNetmask + "&lbdevicecapacity=" + capacity + "&publicipvlan=" + publicIPVlanTag + "&publicipgateway=" + publicIPgateway; ExternalLoadBalancerDeviceVO lbAppliance = null; try { lbAppliance = addExternalLoadBalancer(physicalNetworkId, url, username, password, createLbAnswer.getDeviceName(), createLbAnswer.getServerResource(), false, false, null, null); } catch (Exception e) { s_logger.error("Failed to add load balancer appliance in to cloudstack due to " + e.getMessage() + ". So provisioned load balancer appliance will be destroyed."); } if (lbAppliance != null) { // mark the load balancer as cloudstack managed and set parent host id on which lb appliance is provisioned ExternalLoadBalancerDeviceVO managedLb = _externalLoadBalancerDeviceDao.findById(lbAppliance.getId()); managedLb.setIsManagedDevice(true); managedLb.setParentHostId(lbProviderDevice.getHostId()); _externalLoadBalancerDeviceDao.update(lbAppliance.getId(), managedLb); } else { // failed to add the provisioned load balancer into cloudstack so destroy the appliance DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbProviderDevice.getHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destroy load balancer appliance created"); } else { // release the public & private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbIP, guestConfig.getDataCenterId(), null); _ipAddrMgr.disassociatePublicIpAddress(publicIp.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance created for the network" + guestConfig.getId() + " due to " + e.getMessage()); } } } } } } } return lbDevice; } @Override public ExternalLoadBalancerDeviceVO findSuitableLoadBalancerForNetwork(Network network, boolean dedicatedLb) throws InsufficientCapacityException { long physicalNetworkId = network.getPhysicalNetworkId(); List lbDevices = null; String provider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Lb); assert (provider != null); if (dedicatedLb) { lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { // return first device that is free, fully configured and meant for dedicated use for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } else { // get the LB devices that are already allocated for shared use lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Shared); if (lbDevices != null) { ExternalLoadBalancerDeviceVO maxFreeCapacityLbdevice = null; long maxFreeCapacity = 0; // loop through the LB device in the physical network and pick the one with maximum free capacity for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { // skip if device is not enabled if (lbdevice.getState() != LBDeviceState.Enabled) { continue; } // get the used capacity from the list of guest networks that are mapped to this load balancer List mappedNetworks = _networkExternalLBDao.listByLoadBalancerDeviceId(lbdevice.getId()); long usedCapacity = ((mappedNetworks == null) || (mappedNetworks.isEmpty())) ? 0 : mappedNetworks.size(); // get the configured capacity for this device long fullCapacity = lbdevice.getCapacity(); if (fullCapacity == 0) { fullCapacity = _defaultLbCapacity; // if capacity not configured then use the default } long freeCapacity = fullCapacity - usedCapacity; if (freeCapacity > 0) { if (maxFreeCapacityLbdevice == null) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } else if (freeCapacity > maxFreeCapacity) { maxFreeCapacityLbdevice = lbdevice; maxFreeCapacity = freeCapacity; } } } // return the device with maximum free capacity and is meant for shared use if (maxFreeCapacityLbdevice != null) { return maxFreeCapacityLbdevice; } } // if we are here then there are no existing LB devices in shared use or the devices in shared use has no // free capacity left // so allocate a new load balancer configured for shared use from the pool of free LB devices lbDevices = _externalLoadBalancerDeviceDao.listByProviderAndDeviceAllocationState(physicalNetworkId, provider, LBDeviceAllocationState.Free); if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbdevice : lbDevices) { if (lbdevice.getState() == LBDeviceState.Enabled && !lbdevice.getIsDedicatedDevice()) { return lbdevice; } } } } // there are no devices which capacity throw new InsufficientNetworkCapacityException("Unable to find a load balancing provider with sufficient capcity " + " to implement the network", Network.class, network.getId()); } @DB protected boolean freeLoadBalancerForNetwork(final Network guestConfig) { GlobalLock deviceMapLock = GlobalLock.getInternLock("LoadBalancerAllocLock"); try { if (deviceMapLock.lock(120)) { ExternalLoadBalancerDeviceVO lbDevice = Transaction.execute(new TransactionCallback() { @Override public ExternalLoadBalancerDeviceVO doInTransaction(TransactionStatus status) { // since network is shutdown remove the network mapping to the load balancer device NetworkExternalLoadBalancerVO networkLBDevice = _networkExternalLBDao.findByNetworkId(guestConfig.getId()); long lbDeviceId = networkLBDevice.getExternalLBDeviceId(); _networkExternalLBDao.remove(networkLBDevice.getId()); List ntwksMapped = _networkExternalLBDao.listByLoadBalancerDeviceId(networkLBDevice.getExternalLBDeviceId()); ExternalLoadBalancerDeviceVO lbDevice = _externalLoadBalancerDeviceDao.findById(lbDeviceId); boolean lbInUse = !(ntwksMapped == null || ntwksMapped.isEmpty()); boolean lbCloudManaged = lbDevice.getIsManagedDevice(); if (!lbInUse && !lbCloudManaged) { // this is the last network mapped to the load balancer device so set device allocation state to be free lbDevice.setAllocationState(LBDeviceAllocationState.Free); _externalLoadBalancerDeviceDao.update(lbDevice.getId(), lbDevice); } // commit the changes before sending agent command to destroy cloudstack managed LB if (!lbInUse && lbCloudManaged) { return lbDevice; } else { return null; } } }); if (lbDevice != null) { // send DestroyLoadBalancerApplianceCommand to the host where load balancer appliance is provisioned Host lbHost = _hostDao.findById(lbDevice.getHostId()); String lbIP = lbHost.getPrivateIpAddress(); DestroyLoadBalancerApplianceCommand lbDeleteCmd = new DestroyLoadBalancerApplianceCommand(lbIP); DestroyLoadBalancerApplianceAnswer answer = null; try { answer = (DestroyLoadBalancerApplianceAnswer)_agentMgr.easySend(lbDevice.getParentHostId(), lbDeleteCmd); if (answer == null || !answer.getResult()) { s_logger.warn("Failed to destoy load balancer appliance used by the network" + guestConfig.getId() + " due to " + answer == null ? "communication error with agent" : answer.getDetails()); } } catch (Exception e) { s_logger.warn("Failed to destroy load balancer appliance used by the network" + guestConfig.getId() + " due to " + e.getMessage()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully destroyed load balancer appliance used for the network" + guestConfig.getId()); } deviceMapLock.unlock(); // remove the provisioned load balancer appliance from cloudstack deleteExternalLoadBalancer(lbHost.getId()); // release the private IP back to dc pool, as the load balancer appliance is now destroyed _dcDao.releasePrivateIpAddress(lbHost.getPrivateIpAddress(), guestConfig.getDataCenterId(), null); // release the public IP allocated for this LB appliance DetailVO publicIpDetail = _hostDetailDao.findDetail(lbHost.getId(), "publicip"); IPAddressVO ipVo = _ipAddressDao.findByIpAndDcId(guestConfig.getDataCenterId(), publicIpDetail.toString()); _ipAddrMgr.disassociatePublicIpAddress(ipVo.getId(), _accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount()); } else { deviceMapLock.unlock(); } return true; } else { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + "as failed to acquire lock "); return false; } } catch (Exception exception) { s_logger.error("Failed to release load balancer device for the network" + guestConfig.getId() + " due to " + exception.getMessage()); } finally { deviceMapLock.releaseRef(); } return false; } private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), network.getId(), ipVO.getId(), privateIp, revoked); staticNats.add(staticNat); StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); element.applyStaticNats(network, staticNats); } private enum MappingState { Create, Remove, Unchanged, }; private class MappingNic { private Nic nic; private MappingState state; public Nic getNic() { return nic; } public void setNic(Nic nic) { this.nic = nic; } public MappingState getState() { return state; } public void setState(MappingState state) { this.state = state; } }; private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { String srcIp = _networkModel.getIp(sourceIpId).getAddress().addr(); InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); Nic loadBalancingIpNic = null; MappingNic nic = new MappingNic(); nic.setState(MappingState.Unchanged); if (!revoked) { if (mapping == null) { // Acquire a new guest IP address and save it as the load balancing IP address String loadBalancingIpAddress = existedGuestIp; if (loadBalancingIpAddress == null) { if (network.getGuestType() == Network.GuestType.Isolated) { loadBalancingIpAddress = _ipAddrMgr.acquireGuestIpAddress(network, null); } else if (network.getGuestType() == Network.GuestType.Shared) { try { PublicIp directIp = _ipAddrMgr.assignPublicIpAddress(network.getDataCenterId(), null, _accountDao.findById(network.getAccountId()), VlanType.DirectAttached, network.getId(), null, true, false); loadBalancingIpAddress = directIp.getAddress().addr(); } catch (InsufficientCapacityException capException) { String msg = "Ran out of guest IP addresses from the shared network."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } if (loadBalancingIpAddress == null) { String msg = "Ran out of guest IP addresses."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } // If a NIC doesn't exist for the load balancing IP address, create one loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); if (loadBalancingIpNic == null) { loadBalancingIpNic = _networkMgr.savePlaceholderNic(network, loadBalancingIpAddress, null, null); } // Save a mapping between the source IP address and the load balancing IP address NIC mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); _inlineLoadBalancerNicMapDao.persist(mapping); // On the firewall provider for the network, create a static NAT rule between the source IP // address and the load balancing IP address try { applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); } catch (ResourceUnavailableException ex) { // Rollback db operation _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); _nicDao.expunge(loadBalancingIpNic.getId()); throw ex; } s_logger.debug("Created static nat rule for inline load balancer"); nic.setState(MappingState.Create); } else { loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); } } else { if (mapping != null) { // Find the NIC that the mapping refers to loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); int count = _ipAddrMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); if (count == 0) { // On the firewall provider for the network, delete the static NAT rule between the source IP // address and the load balancing IP address applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIPv4Address()); // Delete the mapping between the source IP address and the load balancing IP address _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); // Delete the NIC _nicDao.expunge(loadBalancingIpNic.getId()); s_logger.debug("Revoked static nat rule for inline load balancer"); nic.setState(MappingState.Remove); } } else { s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); nic.setNic(null); return nic; } } nic.setNic(loadBalancingIpNic); return nic; } public boolean isNccServiceProvider(Network network) { NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if(null!= networkOffering && networkOffering.getServicePackage() != null ) { return true; } else { return false; } } public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) { long zoneId = guestConfig.getDataCenterId(); return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter); } @Override public boolean applyLoadBalancerRules(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return true; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return true; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return true; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); String srcIpVlan = null; String srcIpGateway = null; String srcIpNetmask = null; Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId(); if(vlanid != null ) { VlanVO publicVlan = _vlanDao.findById(vlanid); srcIpVlan = publicVlan.getVlanTag(); srcIpGateway = publicVlan.getVlanGateway(); srcIpNetmask = publicVlan.getVlanNetmask(); } int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long ipId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, ipId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancer.setNetworkId(network.getId()); loadBalancer.setSrcIpVlan(srcIpVlan); loadBalancer.setSrcIpNetmask(srcIpNetmask); loadBalancer.setSrcIpGateway(srcIpGateway); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } } catch (Exception ex) { if (externalLoadBalancerIsInline) { s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); // Rollback static NAT operation in current session for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); MappingState state = mappingStates.get(i); boolean revoke; if (state == MappingState.Create) { revoke = true; } else if (state == MappingState.Remove) { revoke = false; } else { continue; } long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); getLoadBalancingIpNic(zone, network, sourceIpId, revoke, existedGuestIp); } } throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; } @Override public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException { if (guestConfig.getTrafficType() != TrafficType.Guest) { s_logger.trace("External load balancer can only be used for guest networks."); return false; } long zoneId = guestConfig.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); HostVO externalLoadBalancer = null; if (add) { ExternalLoadBalancerDeviceVO lbDeviceVO = null; // on restart network, device could have been allocated already, skip allocation if a device is assigned lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { // allocate a load balancer device for the network lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { // find the load balancer device allocated for the network ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); assert (externalLoadBalancer != null) : "There is no device assigned to this network how did shutdown network ended up here??"; } // Send a command to the external load balancer to implement or shutdown the guest network String guestVlanTag = BroadcastDomainType.getValue(guestConfig.getBroadcastUri()); String selfIp = null; String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { // on restart network, network could have already been implemented. If already implemented then return Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic != null) { return true; } // Acquire a self-ip address from the guest network IP address range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { String msg = "failed to acquire guest IP address so not implementing the network on the external load balancer "; s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId()); } } else { // get the self-ip used by the load balancer Nic selfipNic = getPlaceholderNic(guestConfig); if (selfipNic == null) { s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed. So just returning."); return true; } selfIp = selfipNic.getIPv4Address(); } // It's a hack, using isOneToOneNat field for indicate if it's inline or not boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, guestVlanTag, selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : null; answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } if (add) { // Insert a new NIC for this guest network to reserve the self IP _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); } else { // release the self-ip obtained from guest network Nic selfipNic = getPlaceholderNic(guestConfig); _nicDao.remove(selfipNic.getId()); // release the load balancer allocated for the network boolean releasedLB = freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId(); s_logger.error(msg); } } if (s_logger.isDebugEnabled()) { Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId()); String action = add ? "implemented" : "shut down"; s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); } return true; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); _defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalLoadBalancerCommand)) { return null; } if(host.getName().equalsIgnoreCase("NetScalerControlCenter")) { host.setType(Host.Type.NetScalerControlCenter); } else { host.setType(Host.Type.ExternalLoadBalancer); } return host; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != com.cloud.host.Host.Type.ExternalLoadBalancer) { return null; } return new DeleteHostAnswer(true); } protected IpDeployer getIpDeployerForInlineMode(Network network) { //We won't deploy IP, instead the firewall in front of us would do it List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); //Only support one provider now if (providers == null) { s_logger.error("Cannot find firewall provider for network " + network.getId()); return null; } if (providers.size() != 1) { s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); return null; } NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); if (!(element instanceof IpDeployer)) { s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); return null; } s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); return (IpDeployer)element; } @Override public List getLBHealthChecks(Network network, List loadBalancingRules) throws ResourceUnavailableException { // Find the external load balancer in this zone long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); if (loadBalancingRules == null || loadBalancingRules.isEmpty()) { return null; } HostVO externalLoadBalancer = null; if(isNccServiceProvider(network)) { externalLoadBalancer = getNetScalerControlCenterForNetwork(network); } else { ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network); if (lbDeviceVO == null) { s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning"); return null; } else { externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); } } boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); return null; } List loadBalancersToApply = new ArrayList(); List mappingStates = new ArrayList(); for (final LoadBalancingRule rule : loadBalancingRules) { boolean revoked = (FirewallRule.State.Revoke.equals(rule.getState())); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); String uuid = rule.getUuid(); String srcIp = rule.getSourceIp().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); if (externalLoadBalancerIsInline) { long sourceIpId = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getId(); MappingNic nic = getLoadBalancingIpNic(zone, network, sourceIpId, revoked, null); mappingStates.add(nic.getState()); Nic loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { continue; } // Change the source IP address for the load balancing rule to // be the load balancing IP address srcIp = loadBalancingIpNic.getIPv4Address(); } if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) { boolean inline = _networkMgr.isNetworkInlineMode(network); LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol()); loadBalancersToApply.add(loadBalancer); } } try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand, network.getId()); long guestVlanTag = Integer.parseInt(BroadcastDomainType.getValue(network.getBroadcastUri())); cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); HealthCheckLBConfigAnswer answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd); // easySend will return null on error return answer == null ? null : answer.getLoadBalancers(); } } catch (Exception ex) { s_logger.error("Exception Occured ", ex); } //null return is handled by clients return null; } private NicVO getPlaceholderNic(Network network) { List guestIps = _nicDao.listByNetworkId(network.getId()); for (NicVO guestIp : guestIps) { // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getVmType() == null && guestIp.getReserver() == null && !guestIp.getIPv4Address().equals(network.getGateway())) { return guestIp; } } return null; } } |
blob | blob, long method | t | t | t | long method | 0 | 14461 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java/#L141-L1311 | 1 | 2433 | 14461 | critical | |
| 2219 | {"message":"YES, I found bad smells","bad smells are":["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @javax.annotation.Generated(value="protoc", comments="annotations:TraceInfo.java.pb.meta") public final class TraceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.TraceInfo) TraceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use TraceInfo.newBuilder() to construct. private TraceInfo(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private TraceInfo() { traceId_ = ""; edgeId_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TraceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); traceId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); edgeId_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } public static final int TRACE_ID_FIELD_NUMBER = 1; private volatile java.lang.Object traceId_; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int EDGE_ID_FIELD_NUMBER = 2; private volatile java.lang.Object edgeId_; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getTraceIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, edgeId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getTraceIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, traceId_); } if (!getEdgeIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, edgeId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.TraceInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.TraceInfo other = (com.facebook.buck.remoteexecution.proto.TraceInfo) obj; boolean result = true; result = result && getTraceId() .equals(other.getTraceId()); result = result && getEdgeId() .equals(other.getEdgeId()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TRACE_ID_FIELD_NUMBER; hash = (53 * hash) + getTraceId().hashCode(); hash = (37 * hash) + EDGE_ID_FIELD_NUMBER; hash = (53 * hash) + getEdgeId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.TraceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.TraceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * Contains tracing information. * * * Protobuf type {@code facebook.remote_execution.TraceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.TraceInfo) com.facebook.buck.remoteexecution.proto.TraceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.TraceInfo.class, com.facebook.buck.remoteexecution.proto.TraceInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.TraceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); traceId_ = ""; edgeId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_TraceInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo build() { com.facebook.buck.remoteexecution.proto.TraceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo buildPartial() { com.facebook.buck.remoteexecution.proto.TraceInfo result = new com.facebook.buck.remoteexecution.proto.TraceInfo(this); result.traceId_ = traceId_; result.edgeId_ = edgeId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.TraceInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.TraceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.TraceInfo other) { if (other == com.facebook.buck.remoteexecution.proto.TraceInfo.getDefaultInstance()) return this; if (!other.getTraceId().isEmpty()) { traceId_ = other.traceId_; onChanged(); } if (!other.getEdgeId().isEmpty()) { edgeId_ = other.edgeId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.TraceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.TraceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object traceId_ = ""; /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public java.lang.String getTraceId() { java.lang.Object ref = traceId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); traceId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public com.google.protobuf.ByteString getTraceIdBytes() { java.lang.Object ref = traceId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); traceId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } traceId_ = value; onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder clearTraceId() { traceId_ = getDefaultInstance().getTraceId(); onChanged(); return this; } /** * * ID for all the trace information corresponding to the current session. * * * string trace_id = 1; */ public Builder setTraceIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); traceId_ = value; onChanged(); return this; } private java.lang.Object edgeId_ = ""; /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public java.lang.String getEdgeId() { java.lang.Object ref = edgeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); edgeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public com.google.protobuf.ByteString getEdgeIdBytes() { java.lang.Object ref = edgeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); edgeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } edgeId_ = value; onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder clearEdgeId() { edgeId_ = getDefaultInstance().getEdgeId(); onChanged(); return this; } /** * * ID of an edge that needs to be closed (ie, added a end point). * * * string edge_id = 2; */ public Builder setEdgeIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); edgeId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.TraceInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.TraceInfo) private static final com.facebook.buck.remoteexecution.proto.TraceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.TraceInfo(); } public static com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public TraceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TraceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.TraceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } |
data class | data class | t | t | t | 0 | 13545 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src-gen/com/facebook/buck/remoteexecution/proto/TraceInfo.java/#L14-L733 | 1 | 2219 | 13545 | minor | ||
| 2469 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ChannelTypeXmlResult { private ChannelType channelType; private ConfigDescription configDescription; private boolean system; public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription) { this(channelType, configDescription, false); } public ChannelTypeXmlResult(ChannelType channelType, ConfigDescription configDescription, boolean system) { this.channelType = channelType; this.configDescription = configDescription; this.system = system; } public ChannelType toChannelType() { return this.channelType; } public ConfigDescription getConfigDescription() { return this.configDescription; } public boolean isSystem() { return system; } @Override public String toString() { return "ChannelTypeXmlResult [channelType=" + channelType + ", configDescription=" + configDescription + "]"; } } |
data class | data class | t | t | t | 0 | 14574 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/core/org.eclipse.smarthome.core.thing.xml/src/main/java/org/eclipse/smarthome/core/thing/xml/internal/ChannelTypeXmlResult.java/#L28-L61 | 1 | 2469 | 14574 | major | ||
| 1293 | {"message":"YES I found bad smells","bad_smells":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | long method, data class | t | t | t | data class | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 1 | 1293 | 10623 | minor | |
| 648 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Clause getClause(Resource resource) { String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource); Version version = ResourceHelper.getVersionAttribute(resource); String type = ResourceHelper.getTypeAttribute(resource); for (Clause clause : clauses) { if (symbolicName.equals(clause.getPath()) && clause.getDeployedVersion().equals(version) && type.equals(clause.getType())) return clause; } return null; } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6380 | https://github.com/apache/aries/blob/52293d20268de7c98833846ded2b70d6476773de/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/archive/ProvisionResourceHeader.java/#L127-L138 | 2 | 648 | 6380 | minor | |
| 399 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface XtypePackage extends EPackage { /** * The package name. * * * @generated */ String eNAME = "xtype"; /** * The package namespace URI. * * * @generated */ String eNS_URI = "http://www.eclipse.org/xtext/xbase/Xtype"; /** * The package namespace name. * * * @generated */ String eNS_PREFIX = "xtype"; /** * The singleton instance of the package. * * * @generated */ XtypePackage eINSTANCE = org.eclipse.xtext.xtype.impl.XtypePackageImpl.init(); /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ int XFUNCTION_TYPE_REF = 0; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Param Types' containment reference list. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__PARAM_TYPES = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The feature id for the 'Return Type' containment reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__RETURN_TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The feature id for the 'Type' reference. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__TYPE = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 2; /** * The feature id for the 'Instance Context' attribute. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 3; /** * The number of structural features of the 'XFunction Type Ref' class. * * * @generated * @ordered */ int XFUNCTION_TYPE_REF_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 4; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ int XCOMPUTED_TYPE_REFERENCE = 1; /** * The feature id for the 'Equivalent' containment reference. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__EQUIVALENT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE__EQUIVALENT; /** * The feature id for the 'Type Provider' attribute. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 0; /** * The number of structural features of the 'XComputed Type Reference' class. * * * @generated * @ordered */ int XCOMPUTED_TYPE_REFERENCE_FEATURE_COUNT = TypesPackage.JVM_SPECIALIZED_TYPE_REFERENCE_FEATURE_COUNT + 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ int XIMPORT_SECTION = 2; /** * The feature id for the 'Import Declarations' containment reference list. * * * @generated * @ordered */ int XIMPORT_SECTION__IMPORT_DECLARATIONS = 0; /** * The number of structural features of the 'XImport Section' class. * * * @generated * @ordered */ int XIMPORT_SECTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ int XIMPORT_DECLARATION = 3; /** * The feature id for the 'Wildcard' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__WILDCARD = 0; /** * The feature id for the 'Extension' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__EXTENSION = 1; /** * The feature id for the 'Static' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__STATIC = 2; /** * The feature id for the 'Imported Type' reference. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_TYPE = 3; /** * The feature id for the 'Member Name' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__MEMBER_NAME = 4; /** * The feature id for the 'Imported Namespace' attribute. * * * @generated * @ordered */ int XIMPORT_DECLARATION__IMPORTED_NAMESPACE = 5; /** * The number of structural features of the 'XImport Declaration' class. * * * @generated * @ordered */ int XIMPORT_DECLARATION_FEATURE_COUNT = 6; /** * The meta object id for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ int IJVM_TYPE_REFERENCE_PROVIDER = 4; /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XFunctionTypeRef XFunction Type Ref}'. * * * @return the meta object for class 'XFunction Type Ref'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef * @generated */ EClass getXFunctionTypeRef(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes Param Types}'. * * * @return the meta object for the containment reference list 'Param Types'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getParamTypes() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ParamTypes(); /** * Returns the meta object for the containment reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType Return Type}'. * * * @return the meta object for the containment reference 'Return Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getReturnType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_ReturnType(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#getType Type}'. * * * @return the meta object for the reference 'Type'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#getType() * @see #getXFunctionTypeRef() * @generated */ EReference getXFunctionTypeRef_Type(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext Instance Context}'. * * * @return the meta object for the attribute 'Instance Context'. * @see org.eclipse.xtext.xtype.XFunctionTypeRef#isInstanceContext() * @see #getXFunctionTypeRef() * @generated */ EAttribute getXFunctionTypeRef_InstanceContext(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XComputedTypeReference XComputed Type Reference}'. * * * @return the meta object for class 'XComputed Type Reference'. * @see org.eclipse.xtext.xtype.XComputedTypeReference * @generated */ EClass getXComputedTypeReference(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider Type Provider}'. * * * @return the meta object for the attribute 'Type Provider'. * @see org.eclipse.xtext.xtype.XComputedTypeReference#getTypeProvider() * @see #getXComputedTypeReference() * @generated */ EAttribute getXComputedTypeReference_TypeProvider(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportSection XImport Section}'. * * * @return the meta object for class 'XImport Section'. * @see org.eclipse.xtext.xtype.XImportSection * @generated */ EClass getXImportSection(); /** * Returns the meta object for the containment reference list '{@link org.eclipse.xtext.xtype.XImportSection#getImportDeclarations Import Declarations}'. * * * @return the meta object for the containment reference list 'Import Declarations'. * @see org.eclipse.xtext.xtype.XImportSection#getImportDeclarations() * @see #getXImportSection() * @generated */ EReference getXImportSection_ImportDeclarations(); /** * Returns the meta object for class '{@link org.eclipse.xtext.xtype.XImportDeclaration XImport Declaration}'. * * * @return the meta object for class 'XImport Declaration'. * @see org.eclipse.xtext.xtype.XImportDeclaration * @generated */ EClass getXImportDeclaration(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isWildcard Wildcard}'. * * * @return the meta object for the attribute 'Wildcard'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isWildcard() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Wildcard(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isExtension Extension}'. * * * @return the meta object for the attribute 'Extension'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isExtension() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Extension(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#isStatic Static}'. * * * @return the meta object for the attribute 'Static'. * @see org.eclipse.xtext.xtype.XImportDeclaration#isStatic() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_Static(); /** * Returns the meta object for the reference '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedType Imported Type}'. * * * @return the meta object for the reference 'Imported Type'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedType() * @see #getXImportDeclaration() * @generated */ EReference getXImportDeclaration_ImportedType(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getMemberName Member Name}'. * * * @return the meta object for the attribute 'Member Name'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getMemberName() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_MemberName(); /** * Returns the meta object for the attribute '{@link org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace Imported Namespace}'. * * * @return the meta object for the attribute 'Imported Namespace'. * @see org.eclipse.xtext.xtype.XImportDeclaration#getImportedNamespace() * @see #getXImportDeclaration() * @generated */ EAttribute getXImportDeclaration_ImportedNamespace(); /** * Returns the meta object for data type '{@link org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider IJvm Type Reference Provider}'. * * * @return the meta object for data type 'IJvm Type Reference Provider'. * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @model instanceClass="org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider" serializeable="false" * @generated */ EDataType getIJvmTypeReferenceProvider(); /** * Returns the factory that creates the instances of the model. * * * @return the factory that creates the instances of the model. * @generated */ XtypeFactory getXtypeFactory(); /** * * Defines literals for the meta objects that represent * * each class, * each feature of each class, * each enum, * and each data type * * * @generated */ interface Literals { /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl XFunction Type Ref}' class. * * * @see org.eclipse.xtext.xtype.impl.XFunctionTypeRefImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXFunctionTypeRef() * @generated */ EClass XFUNCTION_TYPE_REF = eINSTANCE.getXFunctionTypeRef(); /** * The meta object literal for the 'Param Types' containment reference list feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__PARAM_TYPES = eINSTANCE.getXFunctionTypeRef_ParamTypes(); /** * The meta object literal for the 'Return Type' containment reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__RETURN_TYPE = eINSTANCE.getXFunctionTypeRef_ReturnType(); /** * The meta object literal for the 'Type' reference feature. * * * @generated */ EReference XFUNCTION_TYPE_REF__TYPE = eINSTANCE.getXFunctionTypeRef_Type(); /** * The meta object literal for the 'Instance Context' attribute feature. * * * @generated */ EAttribute XFUNCTION_TYPE_REF__INSTANCE_CONTEXT = eINSTANCE.getXFunctionTypeRef_InstanceContext(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl XComputed Type Reference}' class. * * * @see org.eclipse.xtext.xtype.impl.XComputedTypeReferenceImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXComputedTypeReference() * @generated */ EClass XCOMPUTED_TYPE_REFERENCE = eINSTANCE.getXComputedTypeReference(); /** * The meta object literal for the 'Type Provider' attribute feature. * * * @generated */ EAttribute XCOMPUTED_TYPE_REFERENCE__TYPE_PROVIDER = eINSTANCE.getXComputedTypeReference_TypeProvider(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportSectionImpl XImport Section}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportSectionImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportSection() * @generated */ EClass XIMPORT_SECTION = eINSTANCE.getXImportSection(); /** * The meta object literal for the 'Import Declarations' containment reference list feature. * * * @generated */ EReference XIMPORT_SECTION__IMPORT_DECLARATIONS = eINSTANCE.getXImportSection_ImportDeclarations(); /** * The meta object literal for the '{@link org.eclipse.xtext.xtype.impl.XImportDeclarationImpl XImport Declaration}' class. * * * @see org.eclipse.xtext.xtype.impl.XImportDeclarationImpl * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getXImportDeclaration() * @generated */ EClass XIMPORT_DECLARATION = eINSTANCE.getXImportDeclaration(); /** * The meta object literal for the 'Wildcard' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__WILDCARD = eINSTANCE.getXImportDeclaration_Wildcard(); /** * The meta object literal for the 'Extension' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__EXTENSION = eINSTANCE.getXImportDeclaration_Extension(); /** * The meta object literal for the 'Static' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__STATIC = eINSTANCE.getXImportDeclaration_Static(); /** * The meta object literal for the 'Imported Type' reference feature. * * * @generated */ EReference XIMPORT_DECLARATION__IMPORTED_TYPE = eINSTANCE.getXImportDeclaration_ImportedType(); /** * The meta object literal for the 'Member Name' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__MEMBER_NAME = eINSTANCE.getXImportDeclaration_MemberName(); /** * The meta object literal for the 'Imported Namespace' attribute feature. * * * @generated */ EAttribute XIMPORT_DECLARATION__IMPORTED_NAMESPACE = eINSTANCE.getXImportDeclaration_ImportedNamespace(); /** * The meta object literal for the 'IJvm Type Reference Provider' data type. * * * @see org.eclipse.xtext.xbase.typing.IJvmTypeReferenceProvider * @see org.eclipse.xtext.xtype.impl.XtypePackageImpl#getIJvmTypeReferenceProvider() * @generated */ EDataType IJVM_TYPE_REFERENCE_PROVIDER = eINSTANCE.getIJvmTypeReferenceProvider(); } } //XtypePackage |
data class | data class, long method | t | t | t | long method | 0 | 4069 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xtype/XtypePackage.java/#L38-L639 | 1 | 399 | 4069 | critical | |
| 1089 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @WeakOuter final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } |
data class | long method, data class | t | t | t | long method | 0 | 9716 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java/#L1049-L1101 | 1 | 1089 | 9716 | minor | |
| 258 | {"message": "YES I found bad smells", "bad smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: int width = (int) Math.ceil(2 / sketch.getRelativeError()); int depth = (int) Math.ceil(-Math.log(1 - sketch.getConfidence()) / Math.log(2)); return new AutoValue_SketchFrequencies_Sketch<>(depth, width, sketch); } |
long method | long method | t | t | t | 0 | 2807 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/sdks/java/extensions/sketching/src/main/java/org/apache/beam/sdk/extensions/sketching/SketchFrequencies.java/#L464-L468 | 1 | 258 | 2807 | minor | ||
| 1891 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers (such as 0.0f, 1.0f) 3. Duplicate code within if statements (within if statement for align variable) 4. Single letter variable names (such as v, n) 5. Complex conditionals within if statements (such as align == 0.0f, align == 1.0f) 6. Inconsistent indentation 7. Use of float instead of double for mathematical operations 8. Lack of comments/documentation explaining the purpose of code or variables 9. Lack of error handling 10. Method performing multiple tasks (calculation and setting of variables) 11. Lack of encapsulation (variables and methods are protected instead of private) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | Long method2 Magic numbers (such as 00f, | t | f | t | 0 | 12314 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 2 | 1891 | 12314 | minor | ||
| 435 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ExprList implements Iterable { private final List expressions ; /** Create a copy which does not share the list of expressions with the original */ public static ExprList copy(ExprList other) { return new ExprList(other) ; } /** Create an ExprList that contains the expressions */ public static ExprList create(Collection exprs) { ExprList exprList = new ExprList() ; exprs.forEach(exprList::add) ; return exprList ; } /** Empty, immutable ExprList */ public static final ExprList emptyList = new ExprList(Collections.emptyList()) ; public ExprList() { expressions = new ArrayList<>() ; } private ExprList(ExprList other) { this() ; expressions.addAll(other.expressions) ; } public ExprList(Expr expr) { this() ; expressions.add(expr) ; } public ExprList(List x) { expressions = x ; } public boolean isSatisfied(Binding binding, ExecutionContext execCxt) { for (Expr expr : expressions) { if ( !expr.isSatisfied(binding, execCxt) ) return false ; } return true ; } public Expr get(int idx) { return expressions.get(idx) ; } public int size() { return expressions.size() ; } public boolean isEmpty() { return expressions.isEmpty() ; } public ExprList subList(int fromIdx, int toIdx) { return new ExprList(expressions.subList(fromIdx, toIdx)) ; } public ExprList tail(int fromIdx) { return subList(fromIdx, expressions.size()) ; } public Set getVarsMentioned() { Set x = new HashSet<>() ; varsMentioned(x) ; return x ; } /** @deprecated Use {@link ExprVars#varsMentioned(Collection, ExprList)} */ @Deprecated public void varsMentioned(Collection acc) { for (Expr expr : expressions) ExprVars.varsMentioned(acc, expr); } /** * Rewrite, applying a node{@literal ->}node transformation */ public ExprList applyNodeTransform(NodeTransform transform) { ExprList x = new ExprList() ; for ( Expr e : expressions) x.add(e.applyNodeTransform(transform)); return x ; } public ExprList copySubstitute(Binding binding) { ExprList x = new ExprList() ; for (Expr expr : expressions ) { expr = expr.copySubstitute(binding) ; x.add(expr) ; } return x ; } public void addAll(ExprList exprs) { expressions.addAll(exprs.getList()) ; } public void add(Expr expr) { expressions.add(expr) ; } public List getList() { return Collections.unmodifiableList(expressions) ; } /** Use only while building ExprList */ public List getListRaw() { return expressions ; } @Override public Iterator iterator() { return expressions.iterator() ; } public void prepareExprs(Context context) { ExprBuild build = new ExprBuild(context) ; // Give each expression the chance to set up (bind functions) for (Expr expr : expressions) Walker.walk(expr, build) ; } @Override public String toString() { return expressions.toString() ; } @Override public int hashCode() { return expressions.hashCode() ; } public boolean equals(ExprList other, boolean bySyntax) { if ( this == other ) return true ; if (expressions.size() != other.expressions.size()) return false; for ( int i = 0 ; i < expressions.size() ; i++ ) { Expr e1 = expressions.get(i) ; Expr e2 = other.expressions.get(i) ; if ( ! e1.equals(e2, bySyntax) ) return false ; } return true ; } @Override public boolean equals(Object other) { if ( this == other ) return true ; if ( ! ( other instanceof ExprList ) ) return false ; ExprList exprs = (ExprList)other ; //return expressions.equals(exprs.expressions) ; return equals((ExprList)other, false) ; } public static ExprList splitConjunction(ExprList exprList1) { ExprList exprList2 = new ExprList() ; for (Expr expr : exprList1) split(exprList2, expr) ; return exprList2 ; } private static ExprList splitConjunction(Expr expr) { ExprList exprList = new ExprList() ; split(exprList, expr) ; return exprList ; } private static void split(ExprList exprList, Expr expr) { // Explode &&-chain to exprlist. while (expr instanceof E_LogicalAnd) { E_LogicalAnd x = (E_LogicalAnd)expr ; Expr left = x.getArg1() ; Expr right = x.getArg2() ; split(exprList, left) ; expr = right ; } // Drop through and add remaining exprList.add(expr) ; } } |
data class | data class, long method | t | t | t | long method | 0 | 4284 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprList.java/#L30-L175 | 1 | 435 | 4284 | major | |
| 2281 | { "output": "YES I found bad smells", "the bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class MetaColumn implements Named { public final String tableCat; public final String tableSchem; public final String tableName; public final String columnName; public final int dataType; public final String typeName; public final Integer columnSize; public final Integer bufferLength = null; public final Integer decimalDigits; public final Integer numPrecRadix; public final int nullable; public final String remarks = null; public final String columnDef = null; public final Integer sqlDataType = null; public final Integer sqlDatetimeSub = null; public final Integer charOctetLength; public final int ordinalPosition; @NotNull public final String isNullable; public final String scopeCatalog = null; public final String scopeSchema = null; public final String scopeTable = null; public final Short sourceDataType = null; @NotNull public final String isAutoincrement = ""; @NotNull public final String isGeneratedcolumn = ""; public MetaColumn( String tableCat, String tableSchem, String tableName, String columnName, int dataType, String typeName, Integer columnSize, Integer decimalDigits, Integer numPrecRadix, int nullable, Integer charOctetLength, int ordinalPosition, String isNullable) { this.tableCat = tableCat; this.tableSchem = tableSchem; this.tableName = tableName; this.columnName = columnName; this.dataType = dataType; this.typeName = typeName; this.columnSize = columnSize; this.decimalDigits = decimalDigits; this.numPrecRadix = numPrecRadix; this.nullable = nullable; this.charOctetLength = charOctetLength; this.ordinalPosition = ordinalPosition; this.isNullable = isNullable; } @Override public String getName() { return columnName; } } |
data class | data class | t | t | t | 0 | 13809 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/jdbc/src/main/java/org/apache/drill/jdbc/impl/DrillMetaImpl.java/#L160-L222 | 1 | 2281 | 13809 | major | ||
| 1814 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, required=true, description="the ID of the network") protected Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the new name for the network") private String name; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, description = "the new display text for the network") private String displayText; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, description = "network domain") private String networkDomain; @Parameter(name = ApiConstants.CHANGE_CIDR, type = CommandType.BOOLEAN, description = "Force update even if CIDR type is different") private Boolean changeCidr; @Parameter(name = ApiConstants.NETWORK_OFFERING_ID, type = CommandType.UUID, entityType = NetworkOfferingResponse.class, description = "network offering ID") private Long networkOfferingId; @Parameter(name = ApiConstants.GUEST_VM_CIDR, type = CommandType.STRING, description = "CIDR for guest VMs, CloudStack allocates IPs to guest VMs only from this CIDR") private String guestVmCidr; @Parameter(name =ApiConstants.Update_IN_SEQUENCE, type=CommandType.BOOLEAN, description = "if true, we will update the routers one after the other. applicable only for redundant router based networks using virtual router as provider") private Boolean updateInSequence; @Parameter(name = ApiConstants.DISPLAY_NETWORK, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the network to the end user or not.", authorized = {RoleType.Admin}) private Boolean displayNetwork; @Parameter(name= ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Setting this to true will cause a forced network update,", authorized = {RoleType.Admin}) private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getNetworkName() { return name; } public String getDisplayText() { return displayText; } public String getNetworkDomain() { return networkDomain; } public Long getNetworkOfferingId() { return networkOfferingId; } public Boolean getChangeCidr() { if (changeCidr != null) { return changeCidr; } return false; } public String getGuestVmCidr() { return guestVmCidr; } public Boolean getDisplayNetwork() { return displayNetwork; } public Boolean getUpdateInSequence(){ if(updateInSequence ==null) return false; else return updateInSequence; } public boolean getForced(){ if(forced==null){ return false; } return forced; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } else { return _networkService.getNetwork(id).getAccountId(); } } @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException { User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId()); Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId()); Network network = _networkService.getNetwork(id); if (network == null) { throw new InvalidParameterValueException("Couldn't find network by ID"); } Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getUpdateInSequence(), getForced()); if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } @Override public String getEventDescription() { StringBuilder eventMsg = new StringBuilder("Updating network: " + getId()); if (getNetworkOfferingId() != null) { Network network = _networkService.getNetwork(getId()); if (network == null) { throw new InvalidParameterValueException("Networkd ID=" + id + " doesn't exist"); } if (network.getNetworkOfferingId() != getNetworkOfferingId()) { NetworkOffering oldOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); NetworkOffering newOff = _entityMgr.findById(NetworkOffering.class, getNetworkOfferingId()); if (newOff == null) { throw new InvalidParameterValueException("Networkd offering ID supplied is invalid"); } eventMsg.append(". Original network offering ID: " + oldOff.getUuid() + ", new network offering ID: " + newOff.getUuid()); } } return eventMsg.toString(); } @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; } @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; } @Override public Long getSyncObjId() { return id; } @Override public void checkUuid() { if (getCustomId() != null) { _uuidMgr.checkUuid(getCustomId(), Network.class); } } } |
data class | Long Method, Data Class | t | f | t | Long Method | 0 | 12067 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java/#L45-L225 | 1 | 1814 | 12067 | minor | |
| 797 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 7568 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 2 | 797 | 7568 | minor | |
| 411 | YES I found bad smells the bad smells are: 1. Magic numbers 2. Dead code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ParserRule getCollectionTypeIdentifierRule() { return getCollectionTypeIdentifierAccess().getRule(); } |
feature envy | Magic numbers2 Dead code3 Feature envy | t | f | t | 0 | 4212 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/services/BacktrackingContentAssistTestLanguageGrammarAccess.java/#L3702-L3704 | 2 | 411 | 4212 | minor | ||
| 2112 | YES I found bad smells The bad smells are: 1. Long method 2. Repeated code 3. Feature envy 4. Magic numbers 5. Confusing variable names 6. Lack of comments/documentation 7. Use of nested conditional statements 8. Use of multiple unnecessary checks and comparisons 9. Inefficient if-else structure | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | Long method2 Repeated code3 Feature envy4 Magic numbers5 Confusing variable names6 Lack of comments/documentation7 Use of nested conditional statements8 Use of multiple unnecessary checks and comparisons 9 Inefficient if-else structure | t | f | t | 0 | 13189 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 2 | 2112 | 13189 | major | ||
| 124 | {"answer": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface PropertyPathPart extends EObject { /** * Returns the value of the 'Name' attribute. * * * If the meaning of the 'Name' attribute isn't clear, * there really should be more of a description here... * * * @return the value of the 'Name' attribute. * @see #setName(String) * @see org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.Bug332217TestLanguagePackage#getPropertyPathPart_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.eclipse.xtext.ui.tests.editor.contentassist.bug332217TestLanguage.PropertyPathPart#getName Name}' attribute. * * * @param value the new value of the 'Name' attribute. * @see #getName() * @generated */ void setName(String value); } // PropertyPathPart |
data class | 'Data Class' | t | t | f | {',D,a,t,a," ",C,l,a,s,s,'} | {',D,t," ",C,'} | 0 | 1552 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/bug332217TestLanguage/PropertyPathPart.java/#L24-L52 | 1 | 124 | 1552 | critical |
| 185 | {"message": "YES I found bad smells", "the bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class Map4 extends Map3 { /** */ private static final long serialVersionUID = 0L; /** */ protected K k4; /** */ protected V v4; /** * Constructs map. */ Map4() { // No-op. } /** * Constructs map. * * @param k1 Key1. * @param v1 Value1. * @param k2 Key2. * @param v2 Value2. * @param k3 Key3. * @param v3 Value3. * @param k4 Key4. * @param v4 Value4. */ Map4(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { super(k1, v1, k2, v2, k3, v3); this.k4 = k4; this.v4 = v4; } /** {@inheritDoc} */ @Override public boolean isFull() { return size() == 4; } /** {@inheritDoc} */ @Nullable @Override public V remove(Object key) { if (F.eq(key, k4)) { V res = v4; v4 = null; k4 = null; return res; } return super.remove(key); } /** {@inheritDoc} */ @Override public int size() { return super.size() + (k4 != null ? 1 : 0); } /** {@inheritDoc} */ @Override public boolean containsKey(Object k) { return super.containsKey(k) || (k4 != null && F.eq(k, k4)); } /** {@inheritDoc} */ @Override public boolean containsValue(Object v) { return super.containsValue(v) || (k4 != null && F.eq(v, v4)); } /** {@inheritDoc} */ @Nullable @Override public V get(Object k) { V v = super.get(k); return v != null ? v : (k4 != null && F.eq(k, k4)) ? v4 : null; } /** * Puts key-value pair into map only if given key is already contained in the map * or there are free slots. * Note that this implementation of {@link Map#put(Object, Object)} does not match * general contract of {@link Map} interface and serves only for internal purposes. * * @param key Key. * @param val Value. * @return Previous value associated with given key. */ @Nullable @Override public V put(K key, V val) throws NullPointerException { V oldVal = get(key); if (k1 == null || F.eq(k1, key)) { k1 = key; v1 = val; } else if (k2 == null || F.eq(k2, key)) { k2 = key; v2 = val; } else if (k3 == null || F.eq(k3, key)) { k3 = key; v3 = val; } else if (k4 == null || F.eq(k4, key)) { k4 = key; v4 = val; } return oldVal; } /** {@inheritDoc} */ @Override public Set> entrySet() { return new AbstractSet>() { @Override public Iterator> iterator() { return new Iterator>() { private int idx; private Entry next; { if (k1 != null) { idx = 1; next = e(k1, v1); } else if (k2 != null) { idx = 2; next = e(k2, v2); } else if (k3 != null) { idx = 3; next = e(k3, v3); } else if (k4 != null) { idx = 4; next = e(k4, v4); } } @Override public boolean hasNext() { return next != null; } @SuppressWarnings("fallthrough") @Override public Entry next() { if (!hasNext()) throw new NoSuchElementException(); Entry old = next; next = null; switch (idx) { case 1: if (k2 != null) { idx = 2; next = e(k2, v2); break; } case 2: if (k3 != null) { idx = 3; next = e(k3, v3); break; } case 3: if (k4 != null) { idx = 4; next = e(k4, v4); break; } } return old; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return Map4.this.size(); } }; } } |
blob | blob, long method | t | t | t | long method | 0 | 2110 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/util/GridLeanMap.java/#L836-L1027 | 1 | 185 | 2110 | minor | |
| 577 | { "message": "YES, I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private Action createAction(final ProjectInfo project, final TeamConfiguration team) { Check.notNull(project, "project"); //$NON-NLS-1$ Check.notNull(team, "team"); //$NON-NLS-1$ final String projectGUID = project.getGUID(); // Omit the team name for the default team final String actionName = team.isDefaultTeam() ? project.getName() : MessageFormat.format( Messages.getString("TeamExplorerControl.ProjectSlashTeamFormat"), //$NON-NLS-1$ project.getName(), team.getTeamName()); final Action action = new Action(actionName) { @Override public void run() { final String beforeChangeProjectGUID = context.getCurrentProjectInfo().getGUID(); if (!projectGUID.equals(beforeChangeProjectGUID) || !team.equals(context.getCurrentTeam())) { context.setCurrentProject(projectGUID); context.setCurrentTeam(team); TFSCommonUIClientPlugin.getDefault().projectOrTeamChanged(); // Only invoke this listener if team project changed if (!projectGUID.equals(beforeChangeProjectGUID)) { final boolean tfvc = context.getCurrentProjectInfo().getSourceControlCapabilityFlags().contains( SourceControlCapabilityFlags.TFS); TFSCommonUIClientPlugin.getDefault().sourceControlChanged(tfvc); } } } }; if (projectGUID.equals(context.getCurrentProjectInfo().getGUID()) && team.equals(context.getCurrentTeam())) { action.setChecked(true); } return action; } |
long method | blob, long method | t | t | t | blob | 0 | 5782 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.client.common.ui/src/com/microsoft/tfs/client/common/ui/controls/teamexplorer/TeamExplorerControl.java/#L607-L647 | 1 | 577 | 5782 | major | |
| 1261 | {"message": "YES I found bad smells", "bad smells are": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Experimental class ValueEncoder { private final ValueSerializer valueSerializer; public ValueEncoder(ValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } /** * Encodes a Java object into a Protobuf encoded value. * * @param unencodedValue Java object to encode. * @return Encoded value of the Java object. */ BasicTypes.EncodedValue encodeValue(Object unencodedValue) { BasicTypes.EncodedValue.Builder builder = BasicTypes.EncodedValue.newBuilder(); if (valueSerializer.supportsPrimitives()) { ByteString customBytes = customSerialize(unencodedValue); return builder.setCustomObjectResult(customBytes).build(); } if (Objects.isNull(unencodedValue)) { builder.setNullResult(NullValue.NULL_VALUE); } else if (Integer.class.equals(unencodedValue.getClass())) { builder.setIntResult((Integer) unencodedValue); } else if (Long.class.equals(unencodedValue.getClass())) { builder.setLongResult((Long) unencodedValue); } else if (Short.class.equals(unencodedValue.getClass())) { builder.setShortResult((Short) unencodedValue); } else if (Byte.class.equals(unencodedValue.getClass())) { builder.setByteResult((Byte) unencodedValue); } else if (Double.class.equals(unencodedValue.getClass())) { builder.setDoubleResult((Double) unencodedValue); } else if (Float.class.equals(unencodedValue.getClass())) { builder.setFloatResult((Float) unencodedValue); } else if (byte[].class.equals(unencodedValue.getClass())) { builder.setBinaryResult(ByteString.copyFrom((byte[]) unencodedValue)); } else if (Boolean.class.equals(unencodedValue.getClass())) { builder.setBooleanResult((Boolean) unencodedValue); } else if (String.class.equals(unencodedValue.getClass())) { builder.setStringResult((String) unencodedValue); } else if (JSONWrapper.class.isAssignableFrom(unencodedValue.getClass())) { builder.setJsonObjectResult(((JSONWrapper) unencodedValue).getJSON()); } else { ByteString customBytes = customSerialize(unencodedValue); if (customBytes != null) { builder.setCustomObjectResult(customBytes); } else { throw new IllegalStateException("We don't know how to handle an object of type " + unencodedValue.getClass() + ": " + unencodedValue); } } return builder.build(); } private ByteString customSerialize(Object unencodedValue) { try { ByteString customBytes = valueSerializer.serialize(unencodedValue); return customBytes; } catch (IOException e) { throw new IllegalStateException(e); } } /** * Decodes a Protobuf encoded value into a Java object. * * @param encodedValue Encoded value to decode. * @return Decoded Java object. */ Object decodeValue(BasicTypes.EncodedValue encodedValue) { switch (encodedValue.getValueCase()) { case BINARYRESULT: return encodedValue.getBinaryResult().toByteArray(); case BOOLEANRESULT: return encodedValue.getBooleanResult(); case BYTERESULT: return (byte) encodedValue.getByteResult(); case DOUBLERESULT: return encodedValue.getDoubleResult(); case FLOATRESULT: return encodedValue.getFloatResult(); case INTRESULT: return encodedValue.getIntResult(); case LONGRESULT: return encodedValue.getLongResult(); case SHORTRESULT: return (short) encodedValue.getShortResult(); case STRINGRESULT: return encodedValue.getStringResult(); case JSONOBJECTRESULT: return JSONWrapper.wrapJSON(encodedValue.getJsonObjectResult()); case NULLRESULT: return null; case CUSTOMOBJECTRESULT: try { return valueSerializer.deserialize(encodedValue.getCustomObjectResult()); } catch (IOException | ClassNotFoundException e) { throw new IllegalStateException(e); } default: throw new IllegalStateException( "Can't decode a value of type " + encodedValue.getValueCase() + ": " + encodedValue); } } /** * Encodes a Java object key and a Java object value into a Protobuf encoded entry. * * @param unencodedKey Java object key to encode. * @param unencodedValue Java object value to encode. * @return Encoded entry of the Java object key and value. */ BasicTypes.Entry encodeEntry(Object unencodedKey, Object unencodedValue) { if (unencodedValue == null) { return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)).build(); } return BasicTypes.Entry.newBuilder().setKey(encodeValue(unencodedKey)) .setValue(encodeValue(unencodedValue)).build(); } } |
blob | blob | t | t | t | 0 | 10505 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-experimental-driver/src/main/java/org/apache/geode/experimental/driver/ValueEncoder.java/#L32-L155 | 1 | 1261 | 10505 | minor | ||
| 1912 | { "output": "YES I found bad smells", "the bad smells are": ["Blob", "Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SetOrderReferenceDetailsRequest extends DelegateRequest implements Serializable { @Override protected SetOrderReferenceDetailsRequest getThis() { return this; } //required parameters private String amazonOrderReferenceId; private String orderAmount; private CurrencyCode orderCurrencyCode; //optional parameters private String platformId; private String sellerNote; private String sellerOrderId; private String storeName; private String supplementaryData; private String customInformation; private Boolean requestPaymentAuthorization; /** * * @param amazonOrderReferenceId * This value is retrieved from the Amazon Button widget * after the buyer has successfully authenticated with Amazon. * * @param orderAmount * Specifies the total amount of the order represented by this order reference. */ public SetOrderReferenceDetailsRequest(String amazonOrderReferenceId, String orderAmount) { this.amazonOrderReferenceId = amazonOrderReferenceId; this.orderAmount = orderAmount; } /** * Overrides the Client's currency code with specified currency code in SetOrderReferenceDetailsRequest * * @param currencyCode * A three-digit currency code, formatted based on the ISO 4217 standard. * * @return currenyCode */ public SetOrderReferenceDetailsRequest setOrderCurrencyCode(CurrencyCode currencyCode) { this.orderCurrencyCode = currencyCode; return this; } /** * Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should not be * provided by merchants creating their own custom integration. * * @param platformId Represents the SellerId of the Solution Provider that developed the platform. * This value should only be provided by Solution Providers. It should * not be provided by merchants creating their own custom integration. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setPlatformId(String platformId) { this.platformId = platformId; return this; } /** * Represents a description of the order that is displayed in emails to the buyer. * * @param sellerNote Represents a description of the order that is displayed in emails to the buyer. * * @return Returns a reference to this object so that methods can be chained together. */ public SetOrderReferenceDetailsRequest setSellerNote(String sellerNote) { this.sellerNote = sellerNote; return this; } /** * The merchant-specified identifier of this order. This is displayed to the * buyer in their emails and transaction history on the Amazon Pay website. * * @param sellerOrderId merchant-specified identifier of the order. * * @return the Seller Order ID */ public SetOrderReferenceDetailsRequest setSellerOrderId(String sellerOrderId) { this.sellerOrderId = sellerOrderId; return this; } /** * The identifier of the store from which the order was placed. This overrides * the default value in Seller Central under Settings > Account Settings. It is * displayed to the buyer in their emails and transaction history on the * Amazon Pay website. * * @param storeName the identifier of the store from which the order was placed. * * @return the Store Name */ public SetOrderReferenceDetailsRequest setStoreName(String storeName) { this.storeName = storeName; return this; } /** * Set the trusted authorization supplementary data. * Use only as directed by Amazon Pay. * * @param supplementaryData Trusted authorization supplementary data (JSON string) * * @return Request object */ public SetOrderReferenceDetailsRequest setSupplementaryData(final String supplementaryData) { this.supplementaryData = supplementaryData; return this; } /** * Any additional information that you want to include with this order reference. * * @param customInformation Additional information that merchant wants to pass for the order. * * @return Custom Information */ public SetOrderReferenceDetailsRequest setCustomInformation(String customInformation) { this.customInformation = customInformation; return this; } /** * * @return AmazonOrderReferenceId */ public String getAmazonOrderReferenceId() { return amazonOrderReferenceId; } /** * * @return OrderAmount */ public String getOrderAmount() { return orderAmount; } /** * * @return OrderCurrencyCode */ public CurrencyCode getOrderCurrencyCode() { return orderCurrencyCode; } /** * * @return PlatformId */ public String getPlatformId() { return platformId; } /** * * @return SellerNote */ public String getSellerNote() { return sellerNote; } /** * * @return SellerOrderId */ public String getSellerOrderId() { return sellerOrderId; } /** * * @return StoreName */ public String getStoreName() { return storeName; } /** * Returns the trusted authorization supplementary data. * * @return supplementaryData as a JSON string */ public String getSupplementaryData() { return supplementaryData; } /** * * @return CustomInformation */ public String getCustomInformation() { return customInformation; } /** *Check if payment authorization has been requested or not * * @return Value of the requestPaymentAuthorization */ public Boolean getRequestPaymentAuthorization() { return requestPaymentAuthorization; } /** * Specifies if the merchants want their buyers to go through multi-factor authentication * * @param requestPaymentAuthorization flag exposed to merchants using which merchants * can enforce their buyers to through multi-factor authentication * * @return Value of the requestPaymentAuthorization */ public SetOrderReferenceDetailsRequest setRequestPaymentAuthorization(Boolean requestPaymentAuthorization) { this.requestPaymentAuthorization = requestPaymentAuthorization; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { return "SetOrderReferenceDetailsRequest{" + "amazonOrderReferenceId=" + amazonOrderReferenceId + ", orderAmount=" + orderAmount + ", orderCurrencyCode=" + orderCurrencyCode + ", platformId=" + platformId + ", sellerNote=" + sellerNote + ", sellerOrderId=" + sellerOrderId + ", storeName=" + storeName + ", supplementaryData=" + supplementaryData + ", customInformation=" + customInformation + ", mwsAuthToken=" + getMwsAuthToken() + '}'; } } |
data class | blob, data class, long method | t | t | f | blob, long method | data class | 0 | 12401 | https://github.com/amzn/amazon-pay-sdk-java/blob/5a3547d00c796aab8f0c8ac12e0310f7a5c4678a/src/com/amazon/pay/request/SetOrderReferenceDetailsRequest.java/#L25-L272 | 1 | 1912 | 12401 | major |
| 2395 | YES I found bad smells the bad smells are: 1. Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | Long method | t | f | t | 0 | 14373 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2395 | 14373 | major | ||
| 3797 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | Long method2 Feature envy | t | f | t | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 2 | 3797 | 9604 | minor | ||
| 284 | {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @ManagedAttributeValueType public interface AclRule extends ManagedAttributeValue { String getIdentity(); ObjectType getObjectType(); LegacyOperation getOperation(); Map getAttributes(); RuleOutcome getOutcome(); } |
data class | blob, data class | t | t | t | blob | 0 | 3039 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AclRule.java/#L31-L39 | 1 | 284 | 3039 | major | |
| 106 | { "output": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HttpExchangeTracer { private final Set includes; /** * Creates a new {@code HttpExchangeTracer} that will use the given {@code includes} * to determine the contents of its traces. * @param includes the includes */ public HttpExchangeTracer(Set includes) { this.includes = includes; } /** * Begins the tracing of the exchange that was initiated by the given {@code request} * being received. * @param request the received request * @return the HTTP trace for the */ public final HttpTrace receivedRequest(TraceableRequest request) { return new HttpTrace(new FilteredTraceableRequest(request)); } /** * Ends the tracing of the exchange that is being concluded by sending the given * {@code response}. * @param trace the trace for the exchange * @param response the response that concludes the exchange * @param principal a supplier for the exchange's principal * @param sessionId a supplier for the id of the exchange's session */ public final void sendingResponse(HttpTrace trace, TraceableResponse response, Supplier principal, Supplier sessionId) { setIfIncluded(Include.TIME_TAKEN, () -> System.currentTimeMillis() - trace.getTimestamp().toEpochMilli(), trace::setTimeTaken); setIfIncluded(Include.SESSION_ID, sessionId, trace::setSessionId); setIfIncluded(Include.PRINCIPAL, principal, trace::setPrincipal); trace.setResponse( new HttpTrace.Response(new FilteredTraceableResponse(response))); } /** * Post-process the given mutable map of request {@code headers}. * @param headers the headers to post-process */ protected void postProcessRequestHeaders(Map> headers) { } private T getIfIncluded(Include include, Supplier valueSupplier) { return this.includes.contains(include) ? valueSupplier.get() : null; } private void setIfIncluded(Include include, Supplier supplier, Consumer consumer) { if (this.includes.contains(include)) { consumer.accept(supplier.get()); } } private Map> getHeadersIfIncluded(Include include, Supplier>> headersSupplier, Predicate headerPredicate) { if (!this.includes.contains(include)) { return new LinkedHashMap<>(); } return headersSupplier.get().entrySet().stream() .filter((entry) -> headerPredicate.test(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private final class FilteredTraceableRequest implements TraceableRequest { private final TraceableRequest delegate; private FilteredTraceableRequest(TraceableRequest delegate) { this.delegate = delegate; } @Override public String getMethod() { return this.delegate.getMethod(); } @Override public URI getUri() { return this.delegate.getUri(); } @Override public Map> getHeaders() { Map> headers = getHeadersIfIncluded( Include.REQUEST_HEADERS, this.delegate::getHeaders, this::includedHeader); postProcessRequestHeaders(headers); return headers; } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } if (name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) { return HttpExchangeTracer.this.includes .contains(Include.AUTHORIZATION_HEADER); } return true; } @Override public String getRemoteAddress() { return getIfIncluded(Include.REMOTE_ADDRESS, this.delegate::getRemoteAddress); } } private final class FilteredTraceableResponse implements TraceableResponse { private final TraceableResponse delegate; private FilteredTraceableResponse(TraceableResponse delegate) { this.delegate = delegate; } @Override public int getStatus() { return this.delegate.getStatus(); } @Override public Map> getHeaders() { return getHeadersIfIncluded(Include.RESPONSE_HEADERS, this.delegate::getHeaders, this::includedHeader); } private boolean includedHeader(String name) { if (name.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { return HttpExchangeTracer.this.includes.contains(Include.COOKIE_HEADERS); } return true; } } } |
blob | blob, data class | t | t | t | data class | 0 | 1407 | https://github.com/spring-projects/spring-boot/blob/2225b362991f225e3a93f00e160526d2b8abdfb2/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/http/HttpExchangeTracer.java/#L38-L183 | 1 | 106 | 1407 | minor | |
| 1951 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy (Multiple calls to isSet methods on external objects) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean equals(TListSentryPrivilegesRequest that) { if (that == null) return false; boolean this_present_protocol_version = true; boolean that_present_protocol_version = true; if (this_present_protocol_version || that_present_protocol_version) { if (!(this_present_protocol_version && that_present_protocol_version)) return false; if (this.protocol_version != that.protocol_version) return false; } boolean this_present_requestorUserName = true && this.isSetRequestorUserName(); boolean that_present_requestorUserName = true && that.isSetRequestorUserName(); if (this_present_requestorUserName || that_present_requestorUserName) { if (!(this_present_requestorUserName && that_present_requestorUserName)) return false; if (!this.requestorUserName.equals(that.requestorUserName)) return false; } boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_authorizableHierarchy = true && this.isSetAuthorizableHierarchy(); boolean that_present_authorizableHierarchy = true && that.isSetAuthorizableHierarchy(); if (this_present_authorizableHierarchy || that_present_authorizableHierarchy) { if (!(this_present_authorizableHierarchy && that_present_authorizableHierarchy)) return false; if (!this.authorizableHierarchy.equals(that.authorizableHierarchy)) return false; } return true; } |
long method | Long method2 Feature envy (Multiple calls to isSet methods on external objects) | t | f | t | 0 | 12534 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TListSentryPrivilegesRequest.java/#L360-L401 | 2 | 1951 | 12534 | major | ||
| 1497 | YES I found bad smells The bad smells are: 1. Long method 2. Magic string 3. Repeated code 4. Lack of abstraction 5. Feature envy 6. Large block of code 7. Poorly named variables and methods 8. Explicit type declaration (should use var instead) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void testGroupByOrderPreservingDescSort() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String tableName = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," + " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')"); conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')"); conn.commit(); QueryBuilder queryBuilder = new QueryBuilder() .setSelectExpression("K1,COUNT(*)") .setSelectColumns(Lists.newArrayList("K1")) .setFullTableName(tableName) .setGroupByClause("K1") .setOrderByClause("K1 DESC"); ResultSet rs = executeQuery(conn, queryBuilder); assertTrue(rs.next()); assertEquals("n", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("j", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertTrue(rs.next()); assertEquals("a", rs.getString(1)); assertEquals(4, rs.getLong(2)); assertFalse(rs.next()); String expectedPhoenixPlan = "CLIENT PARALLEL 1-WAY REVERSE FULL SCAN OVER " + tableName + "\n" + " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]"; validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null); } |
long method | Long method2 Magic string3 Repeated code4 Lack of abstraction5 Feature envy6 Large block of code7 Poorly named variables and methods8 Explicit type declaration (should use var instead) | t | f | t | 0 | 11126 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateIT.java/#L386-L427 | 2 | 1497 | 11126 | minor | ||
| 1405 | {"message": "YES I found bad smells", "bad_smells": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | Blob, Data Class | t | f | t | Blob | 0 | 10874 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 1 | 1405 | 10874 | major | |
| 877 | { "answer": "YES I found bad smells", "detected_bad_smells": ["Blob", "Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Shape { private String type; private Map members = Collections.emptyMap(); private String documentation; private List required; private List enumValues; private String payload; private boolean flattened; private boolean exception; private boolean streaming; private boolean wrapper; private Member listMember; private Member mapKeyType; private Member mapValueType; @JsonProperty(value = "error") private ErrorTrait errorTrait; private long min; private long max; private String pattern; private boolean fault; private boolean deprecated; @JsonProperty(value = "eventstream") private boolean isEventStream; @JsonProperty(value = "event") private boolean isEvent; private String timestampFormat; private boolean sensitive; public boolean isFault() { return fault; } public void setFault(boolean fault) { this.fault = fault; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getMembers() { return members; } public void setMembers(Map members) { this.members = members; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public List getRequired() { return required; } public void setRequired(List required) { this.required = required; } public List getEnumValues() { return enumValues; } @JsonProperty(value = "enum") public void setEnumValues(List enumValues) { this.enumValues = enumValues; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public boolean isFlattened() { return flattened; } public void setFlattened(boolean flattened) { this.flattened = flattened; } public boolean isException() { return exception; } public void setException(boolean exception) { this.exception = exception; } public Member getMapKeyType() { return mapKeyType; } @JsonProperty(value = "key") public void setMapKeyType(Member mapKeyType) { this.mapKeyType = mapKeyType; } public Member getMapValueType() { return mapValueType; } @JsonProperty(value = "value") public void setMapValueType(Member mapValueType) { this.mapValueType = mapValueType; } public Member getListMember() { return listMember; } @JsonProperty(value = "member") public void setListMember(Member listMember) { this.listMember = listMember; } public long getMin() { return min; } public void setMin(long min) { this.min = min; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } public boolean isWrapper() { return wrapper; } public void setWrapper(boolean wrapper) { this.wrapper = wrapper; } public ErrorTrait getErrorTrait() { return errorTrait; } public void setErrorTrait(ErrorTrait errorTrait) { this.errorTrait = errorTrait; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public boolean isEventStream() { return isEventStream; } public void setIsEventStream(boolean eventStream) { isEventStream = eventStream; } public boolean isEvent() { return isEvent; } public void setIsEvent(boolean event) { isEvent = event; } public String getTimestampFormat() { return timestampFormat; } public void setTimestampFormat(String timestampFormat) { this.timestampFormat = timestampFormat; } public boolean isSensitive() { return sensitive; } public void setSensitive(boolean sensitive) { this.sensitive = sensitive; } } |
blob | blob, data class | t | t | t | data class | 0 | 8011 | https://github.com/aws/aws-sdk-java-v2/blob/1d5d11e8087c93ab1a3a2d35193052e526fd123c/codegen/src/main/java/software/amazon/awssdk/codegen/model/service/Shape.java/#L23-L261 | 1 | 877 | 8011 | minor | |
| 1665 | { "output": { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 11622 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 1 | 1665 | 11622 | minor | |
| 949 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public void processElement(Object untypedElem) throws Exception { WindowedValue elem = (WindowedValue) untypedElem; Collection windows = windowFn.assignWindows( windowFn.new AssignContext() { @Override public T element() { return elem.getValue(); } @Override public Instant timestamp() { return elem.getTimestamp(); } @Override public BoundedWindow window() { return Iterables.getOnlyElement(elem.getWindows()); } }); WindowedValue res = WindowedValue.of(elem.getValue(), elem.getTimestamp(), windows, elem.getPane()); receiver.process(res); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8517 | https://github.com/apache/beam/blob/a956ff77a8448e5f2c12f6695fec608348b5ab60/runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/AssignWindowsParDoFnFactory.java/#L93-L120 | 2 | 949 | 8517 | minor | ||
| 2117 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | 1. long method | t | t | t | 0 | 13197 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 1 | 2117 | 13197 | major | ||
| 199 | { "response": "YES I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 2 | 199 | 2241 | critical | |
| 1090 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { if (countParagraphs(ranges) > 0) { xhtml.startElement("div", "class", type); ListManager listManager = new ListManager(document); for (Range r : ranges) { if (r != null) { for (int i = 0; i < r.numParagraphs(); i++) { Paragraph p = r.getParagraph(i); i += handleParagraph(p, 0, r, document, FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); } } } xhtml.endElement("div"); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 9724 | https://github.com/apache/tika/blob/4131c6e30f2e0eb1feb85e0f7576531d4e830468/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java/#L248-L266 | 2 | 1090 | 9724 | minor | ||
| 995 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } } |
long method | long method, blob | t | t | t | blob | 0 | 9092 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/area/AreaTreeParser.java/#L260-L323 | 1 | 995 | 9092 | major | |
| 1254 | {"message": "YES, I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 10475 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 1254 | 10475 | minor | |
| 782 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { ensureObj(obj); if (isFinal) { throwFinalFieldIllegalAccessException(value); } if (value == null) { throwSetIllegalArgumentException(value); } if (value instanceof Byte) { unsafe.putInt(obj, fieldOffset, ((Byte) value).byteValue()); return; } if (value instanceof Short) { unsafe.putInt(obj, fieldOffset, ((Short) value).shortValue()); return; } if (value instanceof Character) { unsafe.putInt(obj, fieldOffset, ((Character) value).charValue()); return; } if (value instanceof Integer) { unsafe.putInt(obj, fieldOffset, ((Integer) value).intValue()); return; } throwSetIllegalArgumentException(value); } |
long method | long method | t | t | t | 0 | 7477 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.base/share/classes/jdk/internal/reflect/UnsafeIntegerFieldAccessorImpl.java/#L72-L99 | 1 | 782 | 7477 | minor | ||
| 709 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6757 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Base64.java/#L391-L438 | 2 | 709 | 6757 | major | ||
| 653 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void run( IAction action ) { if ( !preGenerate( ) ) { return; } IFile file = getSelectedFile( ); if ( file != null ) { String url = file.getLocation( ).toOSString( ); Map options = new HashMap( ); options.put( WebViewer.RESOURCE_FOLDER_KEY, ReportPlugin.getDefault( ) .getResourceFolder( file.getProject( ) ) ); options.put( WebViewer.SERVLET_NAME_KEY, WebViewer.VIEWER_DOCUMENT ); Object adapter = ElementAdapterManager.getAdapter( action, IPreviewAction.class ); if ( adapter instanceof IPreviewAction ) { IPreviewAction delegate = (IPreviewAction) adapter; delegate.setProperty( IPreviewConstants.REPORT_PREVIEW_OPTIONS, options ); delegate.setProperty( IPreviewConstants.REPORT_FILE_PATH, url ); delegate.run( ); return; } try { WebViewer.display( url, options ); } catch ( Exception e ) { ExceptionUtil.handle( e ); return; } } else { action.setEnabled( false ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 6389 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.preview.web/src/org/eclipse/birt/report/designer/ui/ide/navigator/GenerateDocumentAction.java/#L39-L87 | 2 | 653 | 6389 | critical | ||
| 602 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class Statement extends RoleElt { @JsonProperty("Sid") public String sid = newSid(); /** * Default effect is Deny; forces callers to switch on Allow. */ @JsonProperty("Effect") public Effects effect; @JsonProperty("Action") public List action = new ArrayList<>(1); @JsonProperty("Resource") public List resource = new ArrayList<>(1); public Statement(final Effects effect) { this.effect = effect; } @Override public void validate() { requireNonNull(sid, "Sid"); requireNonNull(effect, "Effect"); checkState(!(action.isEmpty()), "Empty Action"); checkState(!(resource.isEmpty()), "Empty Resource"); } public Statement setAllowed(boolean f) { effect = effect(f); return this; } public Statement addActions(String... actions) { Collections.addAll(action, actions); return this; } public Statement addActions(Collection actions) { action.addAll(actions); return this; } public Statement addResources(String... resources) { Collections.addAll(resource, resources); return this; } /** * Add a list of resources. * @param resources resource list * @return this statement. */ public Statement addResources(Collection resources) { resource.addAll(resources); return this; } } |
data class | data class | t | t | t | 0 | 6009 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/RoleModel.java/#L284-L342 | 1 | 602 | 6009 | major | ||
| 2047 | YES I found bad smells the bad smells are: 1. Long method 2. Data class 3. Primitive obsession 4. Feature envy 5. Dead code 6. Inconsistent indentation 7. Magic numbers 8. Code duplication 9. Large parameter list 10. Improper naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | Long method2 Data class3 Primitive obsession4 Feature envy5 Dead code6 Inconsistent indentation7 Magic numbers8 Code duplication9 Large parameter list | t | f | t | 0 | 12877 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 2 | 2047 | 12877 | major | ||
| 232 | {"message": "YES, I found bad smells", "bad smells are": ["Long method", "Feature envy"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public GSSCredentialSpi getCredentialElement(GSSNameSpi name, int initLifetime, int acceptLifetime, int usage) throws GSSException { if (name != null && !(name instanceof GssNameElement)) { name = GssNameElement.getInstance(name.toString(), name.getStringNameType()); } GssCredElement credElement; if (usage == GSSCredential.INITIATE_ONLY) { credElement = GssInitCred.getInstance(caller, (GssNameElement) name, initLifetime); } else if (usage == GSSCredential.ACCEPT_ONLY) { credElement = GssAcceptCred.getInstance(caller, (GssNameElement) name, acceptLifetime); } else if (usage == GSSCredential.INITIATE_AND_ACCEPT) { throw new GSSException(GSSException.FAILURE, -1, "Unsupported usage mode: INITIATE_AND_ACCEPT"); } else { throw new GSSException(GSSException.FAILURE, -1, "Unknown usage mode: " + usage); } return credElement; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 2538 | https://github.com/apache/directory-kerby/blob/19fa650424f60d23d1c1bf0af4bb80ffcb8d8843/kerby-kerb/kerb-gssapi/src/main/java/org/apache/kerby/kerberos/kerb/gss/GssMechFactory.java/#L113-L135 | 2 | 232 | 2538 | minor | |
| 766 | YES I found bad smells The bad smells are: 1. Long method 2. Duplicate code 3. Primitive obsession 4. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Duplicate code3 Primitive obsession4 Feature envy | t | f | t | 0 | 7185 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 766 | 7185 | major | ||
| 2180 | { "message": "YES I found bad smells", "bad_smells": [ { "smell": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void sessionEnd0(@Nullable IgniteInternalTx tx, boolean threwEx) throws IgniteCheckedException { try { if (tx == null) { if (sesLsnrs != null && sesHolder.get().contains(store)) { for (CacheStoreSessionListener lsnr : sesLsnrs) lsnr.onSessionEnd(locSes, !threwEx); } if (!sesHolder.get().ended(store)) store.sessionEnd(!threwEx); } } catch (Exception e) { if (!threwEx) throw U.cast(e); } finally { if (sesHolder != null) sesHolder.set(null); } } |
long method | smell: long method | t | t | t | 0 | 13413 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/store/GridCacheStoreManagerAdapter.java/#L928-L948 | 1 | 2180 | 13413 | minor | ||
| 3389 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 6567 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 3389 | 6567 | minor | ||
| 1154 | YES I found bad smells the bad smells are:1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int setPath(Path2D path) { Rectangle2D bounds = path.getBounds2D(); PathIterator it = path.getPathIterator(null); List segInfo = new ArrayList<>(); List pntInfo = new ArrayList<>(); boolean isClosed = false; int numPoints = 0; while (!it.isDone()) { double[] vals = new double[6]; int type = it.currentSegment(vals); switch (type) { case PathIterator.SEG_MOVETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_MOVETO); numPoints++; break; case PathIterator.SEG_LINETO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); numPoints++; break; case PathIterator.SEG_CUBICTO: pntInfo.add(new Point2D.Double(vals[0], vals[1])); pntInfo.add(new Point2D.Double(vals[2], vals[3])); pntInfo.add(new Point2D.Double(vals[4], vals[5])); segInfo.add(SEGMENTINFO_CUBICTO); segInfo.add(SEGMENTINFO_ESCAPE2); numPoints++; break; case PathIterator.SEG_QUADTO: //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); break; case PathIterator.SEG_CLOSE: pntInfo.add(pntInfo.get(0)); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_ESCAPE); segInfo.add(SEGMENTINFO_LINETO); segInfo.add(SEGMENTINFO_CLOSE); isClosed = true; numPoints++; break; default: LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); break; } it.next(); } if(!isClosed) { segInfo.add(SEGMENTINFO_LINETO); } segInfo.add(SEGMENTINFO_END); AbstractEscherOptRecord opt = getEscherOptRecord(); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); verticesProp.setNumberOfElementsInArray(pntInfo.size()); verticesProp.setNumberOfElementsInMemory(pntInfo.size()); verticesProp.setSizeOfElements(8); for (int i = 0; i < pntInfo.size(); i++) { Point2D.Double pnt = pntInfo.get(i); byte[] data = new byte[8]; LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); verticesProp.setElement(i, data); } opt.addEscherProperty(verticesProp); EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); segmentsProp.setNumberOfElementsInArray(segInfo.size()); segmentsProp.setNumberOfElementsInMemory(segInfo.size()); segmentsProp.setSizeOfElements(0x2); for (int i = 0; i < segInfo.size(); i++) { byte[] seg = segInfo.get(i); segmentsProp.setElement(i, seg); } opt.addEscherProperty(segmentsProp); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); opt.sortProperties(); setAnchor(bounds); return numPoints; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10137 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java/#L107-L198 | 2 | 1154 | 10137 | critical | |
| 1753 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Map< String, String > listLanguages(PageContext pageContext) { Map< String, String > resultMap = new LinkedHashMap<>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); List< String > entries = ClassUtil.classpathEntriesUnder( DIRECTORY ); for( String name : entries ) { if ( name.equals( I18NRESOURCE_EN ) || (name.startsWith( I18NRESOURCE_PREFIX ) && name.endsWith( I18NRESOURCE_SUFFIX ) ) ) { if (name.equals( I18NRESOURCE_EN )) { name = I18NRESOURCE_EN_ID; } else { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); } Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } return resultMap; } |
long method | Long Method, Feature Envy | t | f | t | Feature Envy | 0 | 11865 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/ui/TemplateManager.java/#L420-L446 | 1 | 1753 | 11865 | minor | |
| 480 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 4632 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 2 | 480 | 4632 | minor | ||
| 2255 | { "response": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ThymeleafAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private String[] excludeMethods; @AutoPopulate private String[] excludeViews; /** * Constructor * * @param governorPhysicalTypeMetadata */ public ThymeleafAnnotationValues(final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, ROO_THYMELEAF); AutoPopulationUtils.populate(this, annotationMetadata); } public String[] getExcludeMethods() { return excludeMethods; } public String[] getExcludeViews() { return excludeViews; } } |
data class | data class | t | t | t | 0 | 13690 | https://github.com/spring-projects/spring-roo/blob/4a2e9f1eb17d4e49ad947503a63afef7d5a37842/addon-web-mvc-thymeleaf/addon/src/main/java/org/springframework/roo/addon/web/mvc/thymeleaf/addon/ThymeleafAnnotationValues.java/#L17-L44 | 1 | 2255 | 13690 | minor | ||
| 1117 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private int addManualRecord(Airing recAir, UIClient uiClient) { // Check to make sure we have an encoder that can receive this station Set tryUs = new HashSet(encoderStateMap.values()); Iterator walker = tryUs.iterator(); // We only need to worry about conflicts with other recordings that occur within the same set of stations. If // encoder A has no intersection with the stations on encoder B; then there's no reason to prompt about conflicts from // that tuner since it won't help resolve scheduling issues. So this set will be all the stations that either directly or // indirectly could resolve a conflict with the new recording. // Due to the indirect nature of this; we have to keep checking through the encoders until this set stops growing in size Set unifiedStationSet = new HashSet(); boolean encoderExists = false; while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (es.stationSet.contains(recAir.stationID)) { encoderExists = true; unifiedStationSet.addAll(es.stationSet); walker.remove(); // to avoid redundant checking below break; } } } if (!encoderExists) return VideoFrame.WATCH_FAILED_NO_ENCODERS_HAVE_STATION; int lastSetSize; do { lastSetSize = unifiedStationSet.size(); walker = tryUs.iterator(); while (walker.hasNext()) { EncoderState es = walker.next(); synchronized (es.stationSet) { if (unifiedStationSet.removeAll(es.stationSet)) { // There was an intersection, so use all of these stations, then ignore this one for later unifiedStationSet.addAll(es.stationSet); walker.remove(); } } } } while (lastSetSize != unifiedStationSet.size() && !tryUs.isEmpty()); long defaultStartPadding = Sage.getLong("default_mr_start_padding", 0); long defaultStopPadding = Sage.getLong("default_mr_stop_padding", 0); long requestedStart = recAir.getStartTime() - defaultStartPadding; long requestedStop = recAir.getEndTime() + defaultStopPadding; long requestedDuration = requestedStop - requestedStart; Airing schedAir = recAir; if (defaultStartPadding != 0 || defaultStopPadding != 0) { schedAir = new Airing(0); schedAir.time = requestedStart; schedAir.duration = requestedDuration; schedAir.stationID = recAir.stationID; schedAir.showID = recAir.showID; } Vector parallelRecords = new Vector(); Vector lastParallel = null; do { parallelRecords.clear(); ManualRecord[] manualMustSee = wiz.getManualRecordsSortedByTime(); Vector parallelRecurs = new Vector(); for (int i = 0; i < manualMustSee.length; i++) { ManualRecord currRec = manualMustSee[i]; if (currRec.getContentAiring() == recAir) return VideoFrame.WATCH_OK; if (currRec.getEndTime() <= Sage.time()) continue; if (currRec.doRecurrencesOverlap(requestedStart, requestedDuration, 0)) { parallelRecords.addElement(manualMustSee[i].getSchedulingAiring()); if (currRec.recur != 0) parallelRecurs.add(currRec); else parallelRecurs.add(null); } } if (parallelRecords.isEmpty()) break; parallelRecords.addElement(schedAir); parallelRecurs.add(null); if (sched.testMultiTunerSchedulingPermutation(parallelRecords)) break; // Remove any recurrence duplicates from the parallel list that is presented to the user for (int i = 0; i < parallelRecurs.size(); i++) { ManualRecord currRecur = parallelRecurs.get(i); if (currRecur == null) continue; for (int j = 0; j < parallelRecords.size(); j++) { if (i == j || parallelRecurs.get(j) == null) continue; ManualRecord otherRecur = parallelRecurs.get(j); if (currRecur.stationID == otherRecur.stationID && currRecur.duration == otherRecur.duration && currRecur.recur == otherRecur.recur && currRecur.isSameRecurrence(otherRecur.startTime)) { parallelRecurs.remove(j); parallelRecords.remove(j); j--; } } } // Conflict exists, we need to kill a recording that's on an encoder that's capable // of recording this // Conflict resolution, ask about what you're going to kill parallelRecords.remove(schedAir); // Remove any items from the conflict options that would not end up in station set overlap either directly or indirectly for (int i = 0; i < parallelRecords.size(); i++) if (!unifiedStationSet.contains(parallelRecords.get(i).stationID)) parallelRecords.remove(i--); // If we have the same conflicts as when we just checked, then bail. Most likely they // aren't processing the Hook correctly and we'll be in an infinite loop. if (lastParallel != null && parallelRecords.equals(lastParallel)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; Object hookRes = (uiClient == null) ? null : uiClient.processUIClientHook("RecordRequestScheduleConflict", new Object[] { recAir, parallelRecords }); if (!(hookRes instanceof Boolean) || !((Boolean) hookRes)) return VideoFrame.WATCH_FAILED_USER_REJECTED_CONFLICT; lastParallel = new Vector(parallelRecords); } while (true); ManualRecord newMR; if (schedAir.getStartTime() < Sage.time()) { int[] errorReturn = new int[1]; EncoderState es = findBestEncoderForNow(schedAir, true, uiClient, errorReturn); if (es == null) { if (errorReturn[0] == 0) errorReturn[0] = VideoFrame.WATCH_FAILED_GENERAL_CANT_FIND_ENCODER; return errorReturn[0]; } synchronized (this) { es = checkForFoundBestEncoderNowRecordSwitch(es, recAir); // Set the acquisition state to manual if it has already started recording MediaFile mf = wiz.getFileForAiring(recAir); if (mf != null) mf.setAcquisitionTech(MediaFile.ACQUISITION_MANUAL); newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); es.forceWatch = newMR.getSchedulingAiring(); es.forceProcessed = false; work(); } } else newMR = wiz.addManualRecord(requestedStart, requestedDuration, 0, recAir.stationID, "", "", recAir.id, 0); PluginEventManager.postEvent(PluginEventManager.MANUAL_RECORD_ADDED, new Object[] { PluginEventManager.VAR_AIRING, newMR.getSchedulingAiring() }); return VideoFrame.WATCH_OK; } |
long method | long method | t | t | t | 0 | 9955 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Seeker.java/#L5483-L5646 | 1 | 1117 | 9955 | critical | ||
| 1136 | { "answer": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) { int totalAscent = (int)(targetSpan * getAlignment(axis)); int totalDescent = targetSpan - totalAscent; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); float align = v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { // if resizable then resize to the best fit // the smallest span possible float minSpan = v.getMinimumSpan(axis); // the largest span possible float maxSpan = v.getMaximumSpan(axis); if (align == 0.0f) { // if the alignment is 0 then we need to fit into the descent viewSpan = Math.max(Math.min(maxSpan, totalDescent), minSpan); } else if (align == 1.0f) { // if the alignment is 1 then we need to fit into the ascent viewSpan = Math.max(Math.min(maxSpan, totalAscent), minSpan); } else { // figure out the span that we must fit into float fitSpan = Math.min(totalAscent / align, totalDescent / (1.0f - align)); // fit into the calculated span viewSpan = Math.max(Math.min(maxSpan, fitSpan), minSpan); } } else { // otherwise use the preferred spans viewSpan = v.getPreferredSpan(axis); } offsets[i] = totalAscent - (int)(viewSpan * align); spans[i] = (int)viewSpan; } } |
long method | long method | t | t | t | 0 | 10058 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/javax/swing/text/BoxView.java/#L956-L996 | 1 | 1136 | 10058 | minor | ||
| 1899 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12355 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 1899 | 12355 | minor | ||
| 1734 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long Method | t | f | t | 0 | 11823 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1734 | 11823 | major | ||
| 2213 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1392 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1392() {} public Customer1392(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1392[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 13526 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1392.java/#L8-L27 | 1 | 2213 | 13526 | minor | ||
| 2011 | { "result": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean isValidSyntax( Object value ) { String strValue; if ( value == null ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, "null" ) ); } return false; } if ( value instanceof String ) { strValue = ( String ) value; } else if ( value instanceof byte[] ) { strValue = Strings.utf8ToString( ( byte[] ) value ); } else { strValue = value.toString(); } // We must have at least '(cp)', '(xr)' or '(ca)' if ( strValue.length() < 4 ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check the opening and closing parenthesis if ( ( strValue.charAt( 0 ) != '(' ) || ( strValue.charAt( strValue.length() - 1 ) != ')' ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } Set keywords = new HashSet<>(); int len = strValue.length() - 1; boolean needKeyword = true; // for ( int i = 1; i < len; /* */) { // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } int pos = i; // Search for a keyword while ( ( i < len ) && Chars.isAlphaASCII( strValue, pos ) ) { pos++; } if ( pos == i ) { // No keyword : error if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } String keyword = strValue.substring( i, pos ); i = pos; if ( !DSE_BITS.contains( keyword ) ) { // Unknown keyword if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } // Check that the keyword has not been met if ( keywords.contains( keyword ) ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } return false; } keywords.add( keyword ); needKeyword = false; // Skip spaces while ( ( i < len ) && ( strValue.charAt( i ) == ' ' ) ) { i++; } // Do we have another keyword ? if ( ( i < len ) && ( strValue.charAt( i ) == '$' ) ) { // yes i++; needKeyword = true; } } // We are done if ( LOG.isDebugEnabled() ) { if ( needKeyword ) { LOG.debug( I18n.err( I18n.ERR_13210_SYNTAX_INVALID, value ) ); } else { LOG.debug( I18n.msg( I18n.MSG_13701_SYNTAX_VALID, value ) ); } } return !needKeyword; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 12750 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/DseTypeSyntaxChecker.java/#L133-L273 | 1 | 2011 | 12750 | critical | |
| 920 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "bad_smells_are": [ "Data Class", "Long Method" ] } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public class ForeignKeyInfo implements Serializable { public class ForeignKeyCol { public String parentTableName; public String parentDatabaseName; public String parentColName; public String childColName; public Integer position; public ForeignKeyCol(String parentTableName, String parentDatabaseName, String parentColName, String childColName, Integer position) { this.parentTableName = parentTableName; this.parentDatabaseName = parentDatabaseName; this.parentColName = parentColName; this.childColName = childColName; this.position = position; } } // Mapping from constraint name to list of foreign keys Map> foreignKeys; String childTableName; String childDatabaseName; public ForeignKeyInfo() {} public ForeignKeyInfo(List fks, String childTableName, String childDatabaseName) { this.childTableName = childTableName; this.childDatabaseName = childDatabaseName; foreignKeys = new TreeMap>(); if (fks == null) { return; } for (SQLForeignKey fk : fks) { if (fk.getFktable_db().equalsIgnoreCase(childDatabaseName) && fk.getFktable_name().equalsIgnoreCase(childTableName)) { ForeignKeyCol currCol = new ForeignKeyCol(fk.getPktable_name(), fk.getPktable_db(), fk.getPkcolumn_name(), fk.getFkcolumn_name(), fk.getKey_seq()); String constraintName = fk.getFk_name(); if (foreignKeys.containsKey(constraintName)) { foreignKeys.get(constraintName).add(currCol); } else { List currList = new ArrayList(); currList.add(currCol); foreignKeys.put(constraintName, currList); } } } } public String getChildTableName() { return childTableName; } public String getChildDatabaseName() { return childDatabaseName; } public Map> getForeignKeys() { return foreignKeys; } public void setChildTableName(String tableName) { this.childTableName = tableName; } public void setChildDatabaseName(String databaseName) { this.childDatabaseName = databaseName; } public void setForeignKeys(Map> foreignKeys) { this.foreignKeys = foreignKeys; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Foreign Keys for " + childDatabaseName+"."+childTableName+":"); sb.append("["); if (foreignKeys != null && foreignKeys.size() > 0) { for (Map.Entry> me : foreignKeys.entrySet()) { sb.append(" {Constraint Name: " + me.getKey() + ","); List currCol = me.getValue(); if (currCol != null && currCol.size() > 0) { for (ForeignKeyCol fkc : currCol) { sb.append (" (Parent Column Name: " + fkc.parentDatabaseName + "."+ fkc.parentTableName + "." + fkc.parentColName + ", Column Name: " + fkc.childColName + ", Key Sequence: " + fkc.position+ "),"); } sb.setLength(sb.length()-1); } sb.append("},"); } sb.setLength(sb.length()-1); } sb.append("]"); return sb.toString(); } } |
data class | bad_smells_are: data class, long method | t | t | t | long method | 0 | 8275 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/ForeignKeyInfo.java/#L37-L136 | 1 | 920 | 8275 | major | |
| 651 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 6384 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 651 | 6384 | major | |
| 1293 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ClientListenerResponse doHandle(OdbcRequest req) { if (!busyLock.enterBusy()) return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle ODBC request because node is stopping: " + req); if (actx != null) AuthorizationContext.context(actx); try { switch (req.command()) { case QRY_EXEC: return executeQuery((OdbcQueryExecuteRequest)req); case QRY_EXEC_BATCH: return executeBatchQuery((OdbcQueryExecuteBatchRequest)req); case STREAMING_BATCH: return dispatchBatchOrdered((OdbcStreamingBatchRequest)req); case QRY_FETCH: return fetchQuery((OdbcQueryFetchRequest)req); case QRY_CLOSE: return closeQuery((OdbcQueryCloseRequest)req); case META_COLS: return getColumnsMeta((OdbcQueryGetColumnsMetaRequest)req); case META_TBLS: return getTablesMeta((OdbcQueryGetTablesMetaRequest)req); case META_PARAMS: return getParamsMeta((OdbcQueryGetParamsMetaRequest)req); case MORE_RESULTS: return moreResults((OdbcQueryMoreResultsRequest)req); } return new OdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Unsupported ODBC request: " + req); } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10623 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcRequestHandler.java/#L221-L266 | 2 | 1293 | 10623 | minor | ||
| 897 | YES I found bad smells the bad smells are: 1.Feature envy, 2.Excessive method length, 3.Long parameter list, 4.Data class, 5.Missing encapsulation. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Entity @Table(name = "ESPM_SUPPLIER") @NamedQueries({ @NamedQuery(name = "Supplier.getAllSuppliers", query = "SELECT s FROM Supplier s"), @NamedQuery(name = "Supplier.getSupplierBySupplierId", query = "SELECT s FROM Supplier s WHERE s.supplierId= :supplierId") }) public class Supplier { /* Supplier ids are generated within a number range starting with 2 */ @TableGenerator(name = "SupplierGenerator", table = "ESPM_ID_GENERATOR", pkColumnName = "GENERATOR_NAME", valueColumnName = "GENERATOR_VALUE", pkColumnValue = "Customer", initialValue = 100000000, allocationSize = 100) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "SupplierGenerator") @Column(name = "SUPPLIER_ID", length = 10) private String supplierId; @Column(name = "EMAIL_ADDRESS", unique = true) private String emailAddress; @Column(name = "PHONE_NUMBER", length = 30) private String phoneNumber; @Column(name = "CITY", length = 40) private String city; @Column(name = "POSTAL_CODE", length = 10) private String postalCode; @Column(name = "STREET", length = 60) private String street; @Column(name = "HOUSE_NUMBER", length = 10) private String houseNumber; @Column(name = "COUNTRY", length = 3) private String country; @Column(name = "SUPPLIER_NAME", length = 80) private String supplierName; public String getSupplierId() { return supplierId; } public void setSupplierId(String id) { this.supplierId = id; } public void setEmailAddress(String param) { this.emailAddress = param; } public String getEmailAddress() { return emailAddress; } public void setPhoneNumber(String param) { this.phoneNumber = param; } public String getPhoneNumber() { return phoneNumber; } public void setCity(String param) { this.city = param; } public String getCity() { return city; } public void setPostalCode(String param) { this.postalCode = param; } public String getPostalCode() { return postalCode; } public void setStreet(String param) { this.street = param; } public String getStreet() { return street; } public void setHouseNumber(String param) { this.houseNumber = param; } public String getHouseNumber() { return houseNumber; } public void setCountry(String param) { this.country = param; } public String getCountry() { return country; } public void setSupplierName(String param) { this.supplierName = param; } public String getSupplierName() { return supplierName; } } |
data class | Feature envy, 2Excessive method length, 3Long parameter list, 4Data class, 5Missing encapsulation | t | f | t | .Feature envy, 2.Excessive method length, 3.Long parameter list, 5.Missing encapsulation. | 0 | 8148 | https://github.com/SAP/cloud-espm-v2/blob/a5254f2e6fea9b7226296fbe19eb30ab99192b8d/espm-cloud-jpa/src/main/java/com/sap/espm/model/Supplier.java/#L13-L123 | 2 | 897 | 8148 | critical | |
| 1349 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 10754 | https://github.com/apache/commons-jxpath/blob/eff47ab8ca52fdbc91d1313cc224324465dd043e/src/main/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java/#L672-L697 | 2 | 1349 | 10754 | minor | ||
| 1896 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FileDiskCacheAttributes extends AbstractDiskCacheAttributes { /** Don't change. */ private static final long serialVersionUID = -7371586172678836062L; /** Default file count limit: -1 means no limit */ public static final int DEFAULT_MAX_NUMBER_OF_FILES = -1; /** Max number of files */ private int maxNumberOfFiles = DEFAULT_MAX_NUMBER_OF_FILES; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_DELETE = 10; /** Max number of retries on delete */ private int maxRetriesOnDelete = DEFAULT_MAX_RETRIES_ON_DELETE; /** Default touch rule. */ public static final boolean DEFAULT_TOUCH_ON_GET = false; /** Default limit on the number of times we will retry a delete. */ public static final int DEFAULT_MAX_RETRIES_ON_TOUCH = 10; /** Max number of retries on touch */ private int maxRetriesOnTouch = DEFAULT_MAX_RETRIES_ON_TOUCH; /** * Should we touch on get. If so, we will reset the last modified time. If you have a max file * size set, this will make the removal strategy LRU. If this is false, then the oldest will be * removed. */ private boolean touchOnGet = DEFAULT_TOUCH_ON_GET; /** * @param maxNumberOfFiles the maxNumberOfFiles to set */ public void setMaxNumberOfFiles( int maxNumberOfFiles ) { this.maxNumberOfFiles = maxNumberOfFiles; } /** * @return the maxNumberOfFiles */ public int getMaxNumberOfFiles() { return maxNumberOfFiles; } /** * @param maxRetriesOnDelete the maxRetriesOnDelete to set */ public void setMaxRetriesOnDelete( int maxRetriesOnDelete ) { this.maxRetriesOnDelete = maxRetriesOnDelete; } /** * @return the maxRetriesOnDelete */ public int getMaxRetriesOnDelete() { return maxRetriesOnDelete; } /** * @param touchOnGet the touchOnGet to set */ public void setTouchOnGet( boolean touchOnGet ) { this.touchOnGet = touchOnGet; } /** * @return the touchOnGet */ public boolean isTouchOnGet() { return touchOnGet; } /** * @param maxRetriesOnTouch the maxRetriesOnTouch to set */ public void setMaxRetriesOnTouch( int maxRetriesOnTouch ) { this.maxRetriesOnTouch = maxRetriesOnTouch; } /** * @return the maxRetriesOnTouch */ public int getMaxRetriesOnTouch() { return maxRetriesOnTouch; } /** * Write out the values for debugging purposes. * * @return String */ @Override public String toString() { StringBuilder str = new StringBuilder(); str.append( "DiskFileCacheAttributes " ); str.append( "\n diskPath = " + super.getDiskPath() ); str.append( "\n maxNumberOfFiles = " + getMaxNumberOfFiles() ); str.append( "\n maxRetriesOnDelete = " + getMaxRetriesOnDelete() ); return str.toString(); } } |
data class | data class | t | t | t | 0 | 12334 | https://github.com/apache/commons-jcs/blob/ad897014842fc830483f32fdfb903f3bb8f70289/commons-jcs-sandbox/filecache/src/main/java/org/apache/commons/jcs/auxiliary/disk/file/FileDiskCacheAttributes.java/#L27-L140 | 1 | 1896 | 12334 | major | ||
| 1260 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gateways"}) public static class GatewayHub { @XmlElement(name = "gateway", namespace = "http://geode.apache.org/schema/cache") protected List gateways; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "bind-address") protected String bindAddress; @XmlAttribute(name = "maximum-time-between-pings") protected String maximumTimeBetweenPings; @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "startup-policy") protected String startupPolicy; @XmlAttribute(name = "manual-start") protected Boolean manualStart; @XmlAttribute(name = "max-connections") protected BigInteger maxConnections; /** * Gets the value of the gateway property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gateway property. * * * For example, to add a new item, do as follows: * * * getGateway().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway } * * */ public List getGateway() { if (gateways == null) { gateways = new ArrayList(); } return this.gateways; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the bindAddress property. * * possible object is * {@link String } * */ public String getBindAddress() { return bindAddress; } /** * Sets the value of the bindAddress property. * * allowed object is * {@link String } * */ public void setBindAddress(String value) { this.bindAddress = value; } /** * Gets the value of the maximumTimeBetweenPings property. * * possible object is * {@link String } * */ public String getMaximumTimeBetweenPings() { return maximumTimeBetweenPings; } /** * Sets the value of the maximumTimeBetweenPings property. * * allowed object is * {@link String } * */ public void setMaximumTimeBetweenPings(String value) { this.maximumTimeBetweenPings = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the startupPolicy property. * * possible object is * {@link String } * */ public String getStartupPolicy() { return startupPolicy; } /** * Sets the value of the startupPolicy property. * * allowed object is * {@link String } * */ public void setStartupPolicy(String value) { this.startupPolicy = value; } /** * Gets the value of the manualStart property. * * possible object is * {@link Boolean } * */ public Boolean isManualStart() { return manualStart; } /** * Sets the value of the manualStart property. * * allowed object is * {@link Boolean } * */ public void setManualStart(Boolean value) { this.manualStart = value; } /** * Gets the value of the maxConnections property. * * possible object is * {@link BigInteger } * */ public BigInteger getMaxConnections() { return maxConnections; } /** * Sets the value of the maxConnections property. * * allowed object is * {@link BigInteger } * */ public void setMaxConnections(BigInteger value) { this.maxConnections = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <choice> * <element name="gateway-endpoint" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * <element name="gateway-listener" maxOccurs="unbounded"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="class-name" type="{http://geode.apache.org/schema/cache}class-name-type"/> * <element name="parameter" type="{http://geode.apache.org/schema/cache}parameter-type" maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </element> * </choice> * <element name="gateway-queue" minOccurs="0"> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * </element> * </sequence> * <attribute name="early-ack" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-buffer-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="socket-read-timeout" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="concurrency-level" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="order-policy" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"gatewayEndpoints", "gatewayListeners", "gatewayQueue"}) public static class Gateway { @XmlElement(name = "gateway-endpoint", namespace = "http://geode.apache.org/schema/cache") protected List gatewayEndpoints; @XmlElement(name = "gateway-listener", namespace = "http://geode.apache.org/schema/cache") protected List gatewayListeners; @XmlElement(name = "gateway-queue", namespace = "http://geode.apache.org/schema/cache") protected CacheConfig.GatewayHub.Gateway.GatewayQueue gatewayQueue; @XmlAttribute(name = "early-ack") protected Boolean earlyAck; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "socket-buffer-size") protected String socketBufferSize; @XmlAttribute(name = "socket-read-timeout") protected String socketReadTimeout; @XmlAttribute(name = "concurrency-level") protected String concurrencyLevel; @XmlAttribute(name = "order-policy") protected String orderPolicy; /** * Gets the value of the gatewayEndpoints property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayEndpoints property. * * * For example, to add a new item, do as follows: * * * getGatewayEndpoints().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link CacheConfig.GatewayHub.Gateway.GatewayEndpoint } * * */ public List getGatewayEndpoints() { if (gatewayEndpoints == null) { gatewayEndpoints = new ArrayList(); } return this.gatewayEndpoints; } /** * Gets the value of the gatewayListeners property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the gatewayListeners property. * * * For example, to add a new item, do as follows: * * * getGatewayListeners().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link DeclarableType } * * */ public List getGatewayListeners() { if (gatewayListeners == null) { gatewayListeners = new ArrayList(); } return this.gatewayListeners; } /** * Gets the value of the gatewayQueue property. * * possible object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public CacheConfig.GatewayHub.Gateway.GatewayQueue getGatewayQueue() { return gatewayQueue; } /** * Sets the value of the gatewayQueue property. * * allowed object is * {@link CacheConfig.GatewayHub.Gateway.GatewayQueue } * */ public void setGatewayQueue(CacheConfig.GatewayHub.Gateway.GatewayQueue value) { this.gatewayQueue = value; } /** * Gets the value of the earlyAck property. * * possible object is * {@link Boolean } * */ public Boolean isEarlyAck() { return earlyAck; } /** * Sets the value of the earlyAck property. * * allowed object is * {@link Boolean } * */ public void setEarlyAck(Boolean value) { this.earlyAck = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the socketBufferSize property. * * possible object is * {@link String } * */ public String getSocketBufferSize() { return socketBufferSize; } /** * Sets the value of the socketBufferSize property. * * allowed object is * {@link String } * */ public void setSocketBufferSize(String value) { this.socketBufferSize = value; } /** * Gets the value of the socketReadTimeout property. * * possible object is * {@link String } * */ public String getSocketReadTimeout() { return socketReadTimeout; } /** * Sets the value of the socketReadTimeout property. * * allowed object is * {@link String } * */ public void setSocketReadTimeout(String value) { this.socketReadTimeout = value; } /** * Gets the value of the concurrencyLevel property. * * possible object is * {@link String } * */ public String getConcurrencyLevel() { return concurrencyLevel; } /** * Sets the value of the concurrencyLevel property. * * allowed object is * {@link String } * */ public void setConcurrencyLevel(String value) { this.concurrencyLevel = value; } /** * Gets the value of the orderPolicy property. * * possible object is * {@link String } * */ public String getOrderPolicy() { return orderPolicy; } /** * Sets the value of the orderPolicy property. * * allowed object is * {@link String } * */ public void setOrderPolicy(String value) { this.orderPolicy = value; } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="host" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="port" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayEndpoint { @XmlAttribute(name = "host", required = true) protected String host; @XmlAttribute(name = "id", required = true) protected String id; @XmlAttribute(name = "port", required = true) protected String port; /** * Gets the value of the host property. * * possible object is * {@link String } * */ public String getHost() { return host; } /** * Sets the value of the host property. * * allowed object is * {@link String } * */ public void setHost(String value) { this.host = value; } /** * Gets the value of the id property. * * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the port property. * * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } } /** * * Java class for anonymous complex type. * * * The following schema fragment specifies the expected content contained within this class. * * * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <attribute name="alert-threshold" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-conflation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="batch-size" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="batch-time-interval" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="enable-persistence" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="disk-store-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="roll-oplogs" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * <attribute name="maximum-queue-memory" type="{http://www.w3.org/2001/XMLSchema}string" /> * <attribute name="overflow-directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * </restriction> * </complexContent> * </complexType> * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class GatewayQueue { @XmlAttribute(name = "alert-threshold") protected String alertThreshold; @XmlAttribute(name = "batch-conflation") protected Boolean batchConflation; @XmlAttribute(name = "batch-size") protected String batchSize; @XmlAttribute(name = "batch-time-interval") protected String batchTimeInterval; @XmlAttribute(name = "enable-persistence") protected Boolean enablePersistence; @XmlAttribute(name = "disk-store-name") protected String diskStoreName; @XmlAttribute(name = "roll-oplogs") protected Boolean rollOplogs; @XmlAttribute(name = "maximum-queue-memory") protected String maximumQueueMemory; @XmlAttribute(name = "overflow-directory") protected String overflowDirectory; /** * Gets the value of the alertThreshold property. * * possible object is * {@link String } * */ public String getAlertThreshold() { return alertThreshold; } /** * Sets the value of the alertThreshold property. * * allowed object is * {@link String } * */ public void setAlertThreshold(String value) { this.alertThreshold = value; } /** * Gets the value of the batchConflation property. * * possible object is * {@link Boolean } * */ public Boolean isBatchConflation() { return batchConflation; } /** * Sets the value of the batchConflation property. * * allowed object is * {@link Boolean } * */ public void setBatchConflation(Boolean value) { this.batchConflation = value; } /** * Gets the value of the batchSize property. * * possible object is * {@link String } * */ public String getBatchSize() { return batchSize; } /** * Sets the value of the batchSize property. * * allowed object is * {@link String } * */ public void setBatchSize(String value) { this.batchSize = value; } /** * Gets the value of the batchTimeInterval property. * * possible object is * {@link String } * */ public String getBatchTimeInterval() { return batchTimeInterval; } /** * Sets the value of the batchTimeInterval property. * * allowed object is * {@link String } * */ public void setBatchTimeInterval(String value) { this.batchTimeInterval = value; } /** * Gets the value of the enablePersistence property. * * possible object is * {@link Boolean } * */ public Boolean isEnablePersistence() { return enablePersistence; } /** * Sets the value of the enablePersistence property. * * allowed object is * {@link Boolean } * */ public void setEnablePersistence(Boolean value) { this.enablePersistence = value; } /** * Gets the value of the diskStoreName property. * * possible object is * {@link String } * */ public String getDiskStoreName() { return diskStoreName; } /** * Sets the value of the diskStoreName property. * * allowed object is * {@link String } * */ public void setDiskStoreName(String value) { this.diskStoreName = value; } /** * Gets the value of the rollOplogs property. * * possible object is * {@link Boolean } * */ public Boolean isRollOplogs() { return rollOplogs; } /** * Sets the value of the rollOplogs property. * * allowed object is * {@link Boolean } * */ public void setRollOplogs(Boolean value) { this.rollOplogs = value; } /** * Gets the value of the maximumQueueMemory property. * * possible object is * {@link String } * */ public String getMaximumQueueMemory() { return maximumQueueMemory; } /** * Sets the value of the maximumQueueMemory property. * * allowed object is * {@link String } * */ public void setMaximumQueueMemory(String value) { this.maximumQueueMemory = value; } /** * Gets the value of the overflowDirectory property. * * possible object is * {@link String } * */ public String getOverflowDirectory() { return overflowDirectory; } /** * Sets the value of the overflowDirectory property. * * allowed object is * {@link String } * */ public void setOverflowDirectory(String value) { this.overflowDirectory = value; } } } } |
data class | blob, data class | t | t | t | blob | 0 | 10504 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-management/src/main/java/org/apache/geode/cache/configuration/CacheConfig.java/#L1636-L2524 | 1 | 1260 | 10504 | minor | |
| 4065 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Multiple return points 4. Excessive comments 5. Nested loops or conditionals 6. Inconsistent formatting and coding style 7. Magic numbers or hardcoded values 8. Violation of the Single Responsibility Principle 9. Complex and unreadable code 10. Lack of documentation or proper naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public CreatePreauthenticatedRequestResponse createPreauthenticatedRequest( CreatePreauthenticatedRequestRequest request) { LOG.trace("Called createPreauthenticatedRequest"); request = CreatePreauthenticatedRequestConverter.interceptRequest(request); com.oracle.bmc.http.internal.WrappedInvocationBuilder ib = CreatePreauthenticatedRequestConverter.fromRequest(client, request); com.google.common.base.Function< javax.ws.rs.core.Response, CreatePreauthenticatedRequestResponse> transformer = CreatePreauthenticatedRequestConverter.fromResponse(); int attempts = 0; while (true) { try { javax.ws.rs.core.Response response = client.post(ib, request.getCreatePreauthenticatedRequestDetails(), request); return transformer.apply(response); } catch (com.oracle.bmc.model.BmcException e) { if (++attempts < MAX_IMMEDIATE_RETRIES_IF_USING_INSTANCE_PRINCIPALS && canRetryRequestIfRefreshableAuthTokenUsed(e)) { continue; } else { throw e; } } } } |
long method | Long method2 Feature envy3 Multiple return points4 Excessive comments5 Nested loops or conditionals6 Inconsistent formatting and coding style7 Magic numbers or hardcoded values8 Violation of the Single Responsibility Principle9 Complex and unreadable code | t | f | t | 0 | 10729 | https://github.com/oracle/oci-java-sdk/blob/76e9cecd7b309d9f12e5efe96c74167c66a98872/bmc-objectstorage/bmc-objectstorage-generated/src/main/java/com/oracle/bmc/objectstorage/ObjectStorageClient.java/#L526-L552 | 2 | 4065 | 10729 | minor | ||
| 5710 | {"message": "YES I found bad smells", "bad smells are": ["1. Long method"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List fromProps(Map m) { List props = new ArrayList(); for (Map.Entry entry : m.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); PropertyType propEl = new PropertyType(); propEl.setName(key); ObjectFactory factory = new ObjectFactory(); if (val.getClass().isArray()) { ArrayType arrayEl = new ArrayType(); propEl.getContent().add(factory.createArray(arrayEl)); for (Object o : normalizeArray(val)) { setValueType(propEl, o); ValueType valueType = new ValueType(); valueType.getContent().add(o.toString()); arrayEl.getValue().add(valueType); } } else if (val instanceof List) { ArrayType listEl = new ArrayType(); propEl.getContent().add(factory.createList(listEl)); handleCollectionValue((Collection) val, propEl, listEl); } else if (val instanceof Set) { ArrayType setEl = new ArrayType(); propEl.getContent().add(factory.createSet(setEl)); handleCollectionValue((Collection) val, propEl, setEl); } else if (val instanceof String || val instanceof Character || val instanceof Boolean || val instanceof Byte) { setValueType(propEl, val); propEl.setValue(val.toString()); } else if (val instanceof Long || val instanceof Double || val instanceof Float || val instanceof Integer || val instanceof Short) { // various numbers.. maybe "val instanceof Number"? setValueType(propEl, val); propEl.setValue(val.toString()); } else { // Don't add this property as the value type is not supported continue; } props.add(propEl); } return props; } |
long method | 1. long method | t | t | f | long method | 0 | 12666 | https://github.com/apache/aries-rsa/blob/f5aa5ca62c3948d7e471c3a839089180650cf4f2/discovery/local/src/main/java/org/apache/aries/rsa/discovery/endpoint/PropertiesMapper.java/#L233-L280 | 2 | 5710 | 12666 | major | |
| 931 | { "message": "YES, I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class _AdministrationWebServiceSoap_QueryBuildAgentsByUri implements ElementSerializable { // No attributes // Elements protected String[] agentUris; public _AdministrationWebServiceSoap_QueryBuildAgentsByUri() { super(); } public _AdministrationWebServiceSoap_QueryBuildAgentsByUri(final String[] agentUris) { // TODO : Call super() instead of setting all fields directly? setAgentUris(agentUris); } public String[] getAgentUris() { return this.agentUris; } public void setAgentUris(String[] value) { this.agentUris = value; } public void writeAsElement( final XMLStreamWriter writer, final String name) throws XMLStreamException { writer.writeStartElement(name); // Elements if (this.agentUris != null) { /* * The element type is an array. */ writer.writeStartElement("agentUris"); for (int iterator0 = 0; iterator0 < this.agentUris.length; iterator0++) { XMLStreamWriterHelper.writeElement( writer, "string", this.agentUris[iterator0]); } writer.writeEndElement(); } writer.writeEndElement(); } } |
data class | data class | t | t | t | 0 | 8355 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core.ws/generated-src/ms/tfs/build/buildservice/_03/_AdministrationWebServiceSoap_QueryBuildAgentsByUri.java/#L31-L88 | 1 | 931 | 8355 | minor | ||
| 256 | { "output": "YES I found bad smells. The bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | 1. data class | t | t | t | 0 | 2765 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 1 | 256 | 2765 | critical | ||
| 1411 | YES, I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void positionWriterAtCheckpoint() { writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), CheckpointType.WRITER); CheckpointData writerData = persistenceManagerService.getCheckpointData(writerChkptDK); try { // check for data in backing store if (writerData != null) { byte[] writertoken = writerData.getRestartToken(); TCCLObjectInputStream writerOIS; try { writerProxy.open((Serializable) dataRepresentationService.toJavaRepresentation(writertoken)); } catch (Exception ex) { // is this what I should be throwing here? throw new BatchContainerServiceException("Cannot read the checkpoint data for [" + step.getId() + "]", ex); } } else { // no chkpt data exists in the backing store writerData = null; try { writerProxy.open(null); } catch (Exception ex) { throw new BatchContainerServiceException("Cannot open the step [" + step.getId() + "]", ex); } } } catch (ClassCastException e) { throw new IllegalStateException("Expected CheckpointData but found" + writerData); } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 10900 | https://github.com/apache/incubator-batchee/blob/d4ad6b76d3013a7eb74fbe062aeac305215d6a36/jbatch/src/main/java/org/apache/batchee/container/impl/controller/chunk/ChunkStepController.java/#L1015-L1042 | 2 | 1411 | 10900 | major | |
| 1637 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 11527 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 2 | 1637 | 11527 | minor | ||
| 2607 | YES I found bad smells the bad smells are: 1.Long method | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static List getUserDetails(String query) { List details = new ArrayList(); if (query != null && !query.isEmpty()) { StringTokenizer allParams = new StringTokenizer(query, "&"); while (allParams.hasMoreTokens()) { String param = allParams.nextToken(); details.add(new BasicNameValuePair(param.substring(0, param.indexOf("=")), param.substring(param.indexOf("=") + 1))); } } return details; } |
long method | Long method | t | f | t | 0 | 15030 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/utils/src/main/java/com/cloud/utils/UriUtils.java/#L198-L210 | 2 | 2607 | 15030 | minor | ||
| 2278 | { "output": "YES I found bad smells. The bad smells are: 2. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { private StatusCode code; private String message; private String detail; public StatusCode getCode() { return code; } public Status setCode(StatusCode code) { this.code = code; return this; } public String getMessage() { return message; } public Status setMessage(String message) { this.message = message; return this; } public String getDetail() { return detail; } public Status setDetail(String detail) { this.detail = detail; return this; } } |
data class | 2. data class | t | t | t | 0 | 13783 | https://github.com/spring-projects/spring-security-saml/blob/fa46190c8c37c2eb24b0fd424263c219ffe27e25/core/src/main/java/org/springframework/security/saml/saml2/authentication/Status.java/#L25-L57 | 1 | 2278 | 13783 | major | ||
| 3797 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Transactional(propagation = Propagation.MANDATORY) public Map> loadBookmarkItemsByBookmarkIds(Collection bookmarkIds) { if (bookmarkIds == null || bookmarkIds.isEmpty()) { return Collections.emptyMap(); } Long listId = daoHelper.createTempLongList(bookmarkIds); Map> itemsMap = new HashMap<>(); getJdbcTemplate().query(loadBookmarksItemsQuery, rs -> { BiologicalDataItem dataItem = BiologicalDataItemDao.BiologicalDataItemParameters.getRowMapper() .mapRow(rs, 0); long bookmarkId = rs.getLong(BookmarkItemParameters.BOOKMARK_ID.name()); if (!itemsMap.containsKey(bookmarkId)) { itemsMap.put(bookmarkId, new ArrayList<>()); } itemsMap.get(bookmarkId).add(dataItem); }, listId); daoHelper.clearTempList(listId); return itemsMap; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 9604 | https://github.com/epam/NGB/blob/340504529fc576eeec92fbae636e437ce486cc4a/server/catgenome/src/main/java/com/epam/catgenome/dao/reference/BookmarkDao.java/#L184-L205 | 1 | 3797 | 9604 | minor | |
| 1906 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: long recoverDrf(OplogEntryIdSet deletedIds, boolean alreadyRecoveredOnce, boolean latestOplog) { File drfFile = this.drf.f; if (drfFile == null) { this.haveRecoveredDrf = true; return 0L; } lockCompactor(); try { if (this.haveRecoveredDrf && !getHasDeletes()) return 0L; // do this while holding lock if (!this.haveRecoveredDrf) { this.haveRecoveredDrf = true; } logger.info("Recovering {} {} for disk store {}.", new Object[] {toString(), drfFile.getAbsolutePath(), getParent().getName()}); this.recoverDelEntryId = DiskStoreImpl.INVALID_ID; boolean readLastRecord = true; CountingDataInputStream dis = null; try { int recordCount = 0; boolean foundDiskStoreRecord = false; FileInputStream fis = null; try { fis = new FileInputStream(drfFile); dis = new CountingDataInputStream(new BufferedInputStream(fis, 32 * 1024), drfFile.length()); boolean endOfLog = false; while (!endOfLog) { if (dis.atEndOfFile()) { endOfLog = true; break; } readLastRecord = false; byte opCode = dis.readByte(); if (logger.isTraceEnabled(LogMarker.PERSIST_RECOVERY_VERBOSE)) { logger.trace(LogMarker.PERSIST_RECOVERY_VERBOSE, "drf byte={} location={}", opCode, Long.toHexString(dis.getCount())); } switch (opCode) { case OPLOG_EOF_ID: // we are at the end of the oplog. So we need to back up one byte dis.decrementCount(); endOfLog = true; break; case OPLOG_DEL_ENTRY_1ID: case OPLOG_DEL_ENTRY_2ID: case OPLOG_DEL_ENTRY_3ID: case OPLOG_DEL_ENTRY_4ID: case OPLOG_DEL_ENTRY_5ID: case OPLOG_DEL_ENTRY_6ID: case OPLOG_DEL_ENTRY_7ID: case OPLOG_DEL_ENTRY_8ID: readDelEntry(dis, opCode, deletedIds, parent); recordCount++; break; case OPLOG_DISK_STORE_ID: readDiskStoreRecord(dis, this.drf.f); foundDiskStoreRecord = true; recordCount++; break; case OPLOG_MAGIC_SEQ_ID: readOplogMagicSeqRecord(dis, this.drf.f, OPLOG_TYPE.DRF); break; case OPLOG_GEMFIRE_VERSION: readGemfireVersionRecord(dis, this.drf.f); recordCount++; break; case OPLOG_RVV: long idx = dis.getCount(); readRVVRecord(dis, this.drf.f, true, latestOplog); recordCount++; break; default: throw new DiskAccessException( String.format("Unknown opCode %s found in disk operation log.", opCode), getParent()); } readLastRecord = true; // @todo // if (rgn.isDestroyed()) { // break; // } } // while } finally { if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } } if (!foundDiskStoreRecord && recordCount > 0) { throw new DiskAccessException( "The oplog file \"" + this.drf.f + "\" does not belong to the init file \"" + getParent().getInitFile() + "\". Drf did not contain a disk store id.", getParent()); } } catch (EOFException ignore) { // ignore since a partial record write can be caused by a crash } catch (IOException ex) { getParent().getCancelCriterion().checkCancelInProgress(ex); throw new DiskAccessException( String.format("Failed to read file during recovery from %s", drfFile.getPath()), ex, getParent()); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Cache was closed", e); } } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug("Oplog::readOplog:Error in recovery as Region was destroyed", e); } } // Add the Oplog size to the Directory Holder which owns this oplog, // so that available space is correctly calculated & stats updated. long byteCount = 0; if (!readLastRecord) { // this means that there was a crash // and hence we should not continue to read // the next oplog this.crashed = true; if (dis != null) { byteCount = dis.getFileLength(); } } else { if (dis != null) { byteCount = dis.getCount(); } } if (!alreadyRecoveredOnce) { setRecoveredDrfSize(byteCount); this.dirHolder.incrementTotalOplogSize(byteCount); } return byteCount; } finally { unlockCompactor(); } } |
long method | long method | t | t | t | 0 | 12380 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/Oplog.java/#L1448-L1589 | 1 | 1906 | 12380 | critical | ||
| 930 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8354 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 2 | 930 | 8354 | minor | ||
| 4213 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code/repetitive code 4. Magic numbers 5. Poor variable naming (e.g. "p") 6. Nested if statements 7. Comments that don't add value or are unnecessary 8. Inconsistent formatting (indentation, spacing) 9. Method with too many responsibilities (violating single responsibility principle) 10. Potential exception handling spaghetti code | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public WikiPage getPageInfo( String page, int version ) throws ProviderException { int latest = findLatestVersion(page); int realVersion; WikiPage p = null; if( version == WikiPageProvider.LATEST_VERSION || version == latest || (version == 1 && latest == -1) ) { // // Yes, we need to talk to the top level directory // to get this version. // // I am listening to Press Play On Tape's guitar version of // the good old C64 "Wizardry" -tune at this moment. // Oh, the memories... // realVersion = (latest >= 0) ? latest : 1; p = super.getPageInfo( page, WikiPageProvider.LATEST_VERSION ); if( p != null ) { p.setVersion( realVersion ); } } else { // // The file is not the most recent, so we'll need to // find it from the deep trenches of the "OLD" directory // structure. // realVersion = version; File dir = findOldPageDir( page ); if( !dir.exists() || !dir.isDirectory() ) { return null; } File file = new File( dir, version+FILE_EXT ); if( file.exists() ) { p = new WikiPage( m_engine, page ); p.setLastModified( new Date(file.lastModified()) ); p.setVersion( version ); } } // // Get author and other metadata information // (Modification date has already been set.) // if( p != null ) { try { Properties props = getPageProperties( page ); String author = props.getProperty( realVersion+".author" ); if ( author == null ) { // we might not have a versioned author because the // old page was last maintained by FileSystemProvider Properties props2 = getHeritagePageProperties( page ); author = props2.getProperty( WikiPage.AUTHOR ); } if ( author != null ) { p.setAuthor( author ); } String changenote = props.getProperty( realVersion+".changenote" ); if( changenote != null ) p.setAttribute( WikiPage.CHANGENOTE, changenote ); // Set the props values to the page attributes setCustomProperties(p, props); } catch( IOException e ) { log.error( "Cannot get author for page"+page+": ", e ); } } return p; } |
feature envy | Long method2 Feature envy3 Duplicate code/repetitive code4 Magic numbers5 Poor variable naming (eg "p")6 Nested if statements7 Comments that don't add value or are unnecessary8 Inconsistent formatting (indentation, spacing)9 Method with too many responsibilities (violating single responsibility principle) | t | f | t | spacing)9. Method with too many responsibilities (violating single responsibility principle) | 0 | 11089 | https://github.com/apache/jspwiki/blob/820684992fa0b736505506d6810fdcdf7ad2dbb5/jspwiki-main/src/main/java/org/apache/wiki/providers/VersioningFileProvider.java/#L540-L631 | 2 | 4213 | 11089 | minor | |
| 2545 | {"response": "YES I found bad smells", "detected_bad_smells": ["1. Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public NestedLoopJoin(IHyracksTaskContext ctx, FrameTupleAccessor accessorOuter, FrameTupleAccessor accessorInner, ITuplePairComparator comparatorsOuter2Inner, int memSize, IPredicateEvaluator predEval, boolean isLeftOuter, IMissingWriter[] missingWriters) throws HyracksDataException { this.accessorInner = accessorInner; this.accessorOuter = accessorOuter; this.appender = new FrameTupleAppender(); this.tpComparator = comparatorsOuter2Inner; this.outBuffer = new VSizeFrame(ctx); this.innerBuffer = new VSizeFrame(ctx); this.appender.reset(outBuffer, true); if (memSize < 3) { throw new HyracksDataException("Not enough memory is available for Nested Loop Join"); } this.outerBufferMngr = new VariableFrameMemoryManager(new VariableFramePool(ctx, ctx.getInitialFrameSize() * (memSize - 2)), FrameFreeSlotPolicyFactory.createFreeSlotPolicy(EnumFreeSlotPolicy.LAST_FIT, memSize - 2)); this.predEvaluator = predEval; this.isReversed = false; this.isLeftOuter = isLeftOuter; if (isLeftOuter) { int innerFieldCount = this.accessorInner.getFieldCount(); missingTupleBuilder = new ArrayTupleBuilder(innerFieldCount); DataOutput out = missingTupleBuilder.getDataOutput(); for (int i = 0; i < innerFieldCount; i++) { missingWriters[i].writeMissing(out); missingTupleBuilder.addFieldEndOffset(); } } else { missingTupleBuilder = null; } FileReference file = ctx.getJobletContext().createManagedWorkspaceFile(this.getClass().getSimpleName() + this.toString()); runFileWriter = new RunFileWriter(file, ctx.getIoManager()); runFileWriter.open(); } |
long method | 1. long method | t | t | t | 0 | 14790 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/hyracks-fullstack/hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/join/NestedLoopJoin.java/#L60-L97 | 1 | 2545 | 14790 | major | ||
| 175 | { "answer": "YES I found bad smells", "bad smells are": [ { "name": "Data Class" }, { "name": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template") private Long id; @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = false, length = 2048, description = "the url to which the ISO would be extracted") private String url; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = false, description = "the ID of the zone where the ISO is originally located") private Long zoneId; @Parameter(name = ApiConstants.MODE, type = CommandType.STRING, required = true, description = "the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } public String getUrl() { return url; } public Long getZoneId() { return zoneId; } public String getMode() { return mode; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } public static String getStaticName() { return s_name; } @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); if (template != null) { return template.getAccountId(); } // invalid id, parent this command to SYSTEM so ERROR events are tracked return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_TEMPLATE_EXTRACT; } @Override public String getEventDescription() { return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.Template; } @Override public Long getInstanceId() { return getId(); } @Override public void execute() { try { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } |
data class | name: data class, name: long method | t | t | t | name: long method | 0 | 2046 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java/#L39-L147 | 1 | 175 | 2046 | major | |
| 1881 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public String[] getPath(final TreeItem swtTreeItem) { return Display.syncExec(new ResultRunnable() { @Override public String[] run() { org.eclipse.swt.widgets.TreeItem swttiDummy = swtTreeItem; LinkedList items = new LinkedList(); while (swttiDummy != null) { items.addFirst(swttiDummy.getText()); swttiDummy = swttiDummy.getParentItem(); } return items.toArray(new String[0]); } }); } |
long method | Long method 2 Feature envy | t | f | t | 0 | 12286 | https://github.com/eclipse/reddeer/blob/59e55d29fc60a672d79df1ad1578badb8a2f8693/plugins/org.eclipse.reddeer.core/src/org/eclipse/reddeer/core/handler/TreeItemHandler.java/#L281-L294 | 2 | 1881 | 12286 | minor | ||
| 1188 | YES, I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public String toString() { return "ExecInfo{" + "id='" + id + '\'' + ", container=" + container + ", processConfig=" + processConfig + ", openStdout='" + openStdout + '\'' + ", openStderr='" + openStderr + '\'' + ", openStdin='" + openStdin + '\'' + ", running='" + running + '\'' + ", exitCode='" + exitCode + '\'' + '}'; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10247 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/ExecInfo.java/#L90-L116 | 2 | 1188 | 10247 | minor | ||
| 443 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LaunchRequest { private String jobName; String jobParameters; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobParameters() { return jobParameters; } public void setJobParameters(String jobParameters) { this.jobParameters = jobParameters; } } |
data class | data class | t | t | t | 0 | 4309 | https://github.com/spring-projects/spring-batch-admin/blob/9e3ad8bff99b8fad8da62426aa7d2959eb841bcf/spring-batch-admin-manager/src/main/java/org/springframework/batch/admin/web/LaunchRequest.java/#L21-L42 | 1 | 443 | 4309 | critical | ||
| 327 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LockMode extends TypesafeEnum { private LockMode(final int value) { super(value); } /** * Do not perform any locking. Items are opened for read or write without * regard to concurrent access by other processes. */ public static final LockMode NONE = new LockMode(0); /** * Wait forever to acquire the lock (or until the thread is interrupted). */ public static final LockMode WAIT_FOREVER = new LockMode(1); /** * Attempt to acquire the lock but return immediately if it could not be * acquired. */ public static final LockMode NO_WAIT = new LockMode(2); } |
data class | data class | t | t | t | 0 | 3381 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/persistence/LockMode.java/#L15-L36 | 1 | 327 | 3381 | minor | ||
| 2254 | { "output": "YES I found bad smells. the bad smells are: 1. Long Method" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void processEmail(EmailData emailData) { if (logger.isTraceEnabled()) { logger.trace("Entered MailManager:processEmail"); } if (mailHost == null || mailHost.length() == 0 || emailData == null || mailToAddresses.length == 0) { logger.error("Required mail server configuration is not specfied."); if (logger.isDebugEnabled()) { logger.debug("Exited MailManager:processEmail: Not sending email as conditions not met"); } return; } Session session = Session.getDefaultInstance(getMailHostConfiguration()); MimeMessage mimeMessage = new MimeMessage(session); String subject = emailData.subject; String message = emailData.message; String mailToList = getMailToAddressesAsString(); try { for (int i = 0; i < mailToAddresses.length; i++) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToAddresses[i])); } if (subject == null) { subject = "Alert from GemFire Admin Agent"; } mimeMessage.setSubject(subject); if (message == null) { message = ""; } mimeMessage.setText(message); Transport.send(mimeMessage); logger.info("Email sent to {}. Subject: {}, Content: {}", new Object[] {mailToList, subject, message}); } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable ex) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); StringBuilder buf = new StringBuilder(); buf.append("An exception occurred while sending email."); buf.append( "Unable to send email. Please check your mail settings and the log file."); buf.append("\n\n").append( String.format("Exception message: %s", ex.getMessage())); buf.append("\n\n").append( "Following email was not delivered:"); buf.append("\n\t") .append(String.format("Mail Host: %s", mailHost)); buf.append("\n\t").append(String.format("From: %s", mailFrom)); buf.append("\n\t").append(String.format("To: %s", mailToList)); buf.append("\n\t").append(String.format("Subject: %s", subject)); buf.append("\n\t").append(String.format("Content: %s", message)); logger.error(buf.toString(), ex); } if (logger.isTraceEnabled()) { logger.trace("Exited MailManager:processEmail"); } } |
long method | 1. long method | t | t | t | 0 | 13687 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/MailManager.java/#L80-L150 | 1 | 2254 | 13687 | major | ||
| 2532 | YES, I found bad smells. The bad smells are: (1) Long method, (2) Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public boolean executeSyncCmsId(NuageVspDeviceVO nuageVspDevice, SyncType syncType) { NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice); if (syncType == SyncType.REGISTER && matchingNuageVspDevice != null) { String cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId()); registerNewNuageVspDevice(nuageVspDevice.getHostId(), cmsId); return true; } String cmsId = findNuageVspCmsIdForDeviceOrHost(nuageVspDevice.getId(), nuageVspDevice.getHostId()); SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(syncType, cmsId); SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd); if (answer != null) { if (answer.getSuccess()) { if (syncType == SyncType.REGISTER || answer.getSyncType() == SyncType.REGISTER) { registerNewNuageVspDevice(nuageVspDevice.getHostId(), answer.getNuageVspCmsId()); } else if (syncType == SyncType.UNREGISTER) { removeLegacyNuageVspDeviceCmsId(nuageVspDevice.getId()); } } else if (syncType == SyncType.AUDIT || syncType == SyncType.AUDIT_ONLY) { s_logger.fatal("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!"); } } return answer != null && answer.getSuccess(); } |
long method | ) Long method, (2) Feature envy | t | f | t | (2) Feature envy. | 0 | 14744 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/plugins/network-elements/nuage-vsp/src/main/java/com/cloud/network/manager/NuageVspManagerImpl.java/#L686-L711 | 2 | 2532 | 14744 | minor | |
| 1238 | YES I found bad smells The bad smells are: 1. Feature envy 2. Long method 3. Duplicate code 4. Magic numbers 5. Inconsistent naming conventions | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Dataset[] generateCoordinates(Dataset angles, final double[] geometricParameters) { if (geometricParameters.length != PARAMETERS) throw new IllegalArgumentException("Need " + PARAMETERS + " parameters"); Dataset[] coords = new Dataset[2]; DoubleDataset x = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); DoubleDataset y = DatasetFactory.zeros(DoubleDataset.class, angles.getShape()); coords[0] = x; coords[1] = y; final double ca = Math.cos(geometricParameters[2]); final double sa = Math.sin(geometricParameters[2]); final IndexIterator it = angles.getIterator(); int i = 0; while (it.hasNext()) { final double t = angles.getElementDoubleAbs(it.index); final double ct = Math.cos(t); final double st = Math.sin(t); x.setAbs(i, geometricParameters[3] + geometricParameters[0]*ca*ct - geometricParameters[1]*sa*st); y.setAbs(i, geometricParameters[4] + geometricParameters[0]*sa*ct + geometricParameters[1]*ca*st); i++; } return coords; } |
feature envy | Feature envy2 Long method3 Duplicate code4 Magic numbers5 Inconsistent naming conventions | t | f | t | 0 | 10397 | https://github.com/eclipse/dawnsci/blob/1131d5c65e9e8ea98141eecee1743cf1053544f4/org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/roi/fitting/EllipseFitter.java/#L486-L512 | 2 | 1238 | 10397 | minor | ||
| 1901 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12362 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 2 | 1901 | 12362 | major | ||
| 1333 | { "output": "YES I found bad smells the bad smells are: 1. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class CurrentCreationalContext { private final ThreadLocal> creationalContext = new ThreadLocal>(); public CreationalContext get() { return creationalContext.get(); } public void set(CreationalContext value) { creationalContext.set(value); } public void remove() { creationalContext.remove(); } } |
blob | 1. blob | t | t | f | blob | 0 | 10719 | https://github.com/apache/openejb/blob/f10c077ade927d73bdbd9ed4cc28b79f58a1cd66/openejb/container/openejb-core/src/main/java/org/apache/openejb/cdi/CurrentCreationalContext.java/#L24-L38 | 1 | 1333 | 10719 | critical | |
| 4765 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12825 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 2 | 4765 | 12825 | minor | ||
| 903 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | long method, data class | t | t | t | data class | 0 | 8170 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 903 | 8170 | critical | |
| 606 | { "output": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static void doRawReceiveFile(File path, int size, InputStream clientInput) throws IOException { // Create a temp file to receive the payload, so we don't need to worry about // partially-received files. The host takes care of deleting temp files. File tempfile = File.createTempFile( AgentUtil.TEMP_PREFIX + path.getName() + "-", ".tmp", path.getParentFile()); FileOutputStream output = new FileOutputStream(tempfile); // Keep track of our starting time so we can enforce a timeout on slow but steady uploads. long receiveStartMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); // Keep track of the total received size to verify the payload. long totalSize = 0; long totalReceiveTimeoutMs = RECEIVE_TIMEOUT_MS + TOTAL_RECEIVE_TIMEOUT_MS_PER_MB * (size / 1024 / 1024); try { int bufferSize = 128 * 1024; byte[] buf = new byte[bufferSize]; while (true) { long currentTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); if (currentTimeMs - receiveStartMs > totalReceiveTimeoutMs) { throw new RuntimeException("Receive failed to complete before timeout."); } int remaining = size - (int) totalSize; if (remaining == 0) { break; } int want = bufferSize; if (want > remaining) { want = remaining; } int got = clientInput.read(buf, 0, want); if (got == -1) { break; } output.write(buf, 0, got); totalSize += got; } } finally { output.close(); } if (totalSize != size) { throw new RuntimeException("Received only " + totalSize + " of " + size + " bytes."); } boolean success = tempfile.renameTo(path); if (!success) { throw new RuntimeException("Failed to rename temp file."); } } |
long method | 1: long method | t | t | t | 0 | 6083 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/agent/AgentMain.java/#L189-L237 | 1 | 606 | 6083 | minor | ||
| 2391 | YES I found bad smells the bad smells are:1.Long method, 2.Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static ImmutableDictionaryReader loadDictionary(PinotDataBuffer dictionaryBuffer, ColumnMetadata metadata, boolean loadOnHeap) { FieldSpec.DataType dataType = metadata.getDataType(); if (loadOnHeap) { String columnName = metadata.getColumnName(); LOGGER.info("Loading on-heap dictionary for column: {}", columnName); } int length = metadata.getCardinality(); switch (dataType) { case INT: return (loadOnHeap) ? new OnHeapIntDictionary(dictionaryBuffer, length) : new IntDictionary(dictionaryBuffer, length); case LONG: return (loadOnHeap) ? new OnHeapLongDictionary(dictionaryBuffer, length) : new LongDictionary(dictionaryBuffer, length); case FLOAT: return (loadOnHeap) ? new OnHeapFloatDictionary(dictionaryBuffer, length) : new FloatDictionary(dictionaryBuffer, length); case DOUBLE: return (loadOnHeap) ? new OnHeapDoubleDictionary(dictionaryBuffer, length) : new DoubleDictionary(dictionaryBuffer, length); case STRING: int numBytesPerValue = metadata.getColumnMaxLength(); byte paddingByte = (byte) metadata.getPaddingCharacter(); return loadOnHeap ? new OnHeapStringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte) : new StringDictionary(dictionaryBuffer, length, numBytesPerValue, paddingByte); case BYTES: numBytesPerValue = metadata.getColumnMaxLength(); return new BytesDictionary(dictionaryBuffer, length, numBytesPerValue); default: throw new IllegalStateException("Illegal data type for dictionary: " + dataType); } } |
long method | Long method, 2Primitive obsession | t | f | t | 2.Primitive obsession | 0 | 14362 | https://github.com/apache/incubator-pinot/blob/d58f8bce4b59de096b4ee9fee61c679482dd1d7d/pinot-core/src/main/java/org/apache/pinot/core/segment/index/column/PhysicalColumnIndexContainer.java/#L143-L182 | 2 | 2391 | 14362 | minor | |
| 1945 | YES I found bad smells The bad smells are: 1. Long method, 2. Data clumps, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method, 2 Data clumps, 3 Feature envy | t | f | t | 2. Data clumps, 3. Feature envy | 0 | 12515 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 1945 | 12515 | minor | |
| 1970 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void reloadExpectedTimeAndConfig(SLACalcStatus slaCalc) throws JPAExecutorException { SLARegistrationBean regBean = SLARegistrationQueryExecutor.getInstance().get( SLARegQuery.GET_SLA_EXPECTED_VALUE_CONFIG, slaCalc.getId()); if (regBean.getExpectedDuration() > 0) { slaCalc.getSLARegistrationBean().setExpectedDuration(regBean.getExpectedDuration()); } if (regBean.getExpectedEnd() != null) { slaCalc.getSLARegistrationBean().setExpectedEnd(regBean.getExpectedEnd()); } if (regBean.getExpectedStart() != null) { slaCalc.getSLARegistrationBean().setExpectedStart(regBean.getExpectedStart()); } if (regBean.getSLAConfigMap().containsKey(OozieClient.SLA_DISABLE_ALERT)) { slaCalc.getSLARegistrationBean().addToSLAConfigMap(OozieClient.SLA_DISABLE_ALERT, regBean.getSLAConfigMap().get(OozieClient.SLA_DISABLE_ALERT)); } if (regBean.getNominalTime() != null) { slaCalc.getSLARegistrationBean().setNominalTime(regBean.getNominalTime()); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12607 | https://github.com/apache/oozie/blob/491e73ee9f941dfb25dfe92121fb033295ef42ee/core/src/main/java/org/apache/oozie/sla/SLACalculatorMemory.java/#L540-L560 | 2 | 1970 | 12607 | minor | ||
| 1301 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static class RowRange { private Text startRow; private Text endRow; public RowRange(KeyExtent ke) { this.startRow = ke.getPrevEndRow(); this.endRow = ke.getEndRow(); } public RowRange(TRowRange trr) { this.startRow = ByteBufferUtil.toText(trr.startRow); this.endRow = ByteBufferUtil.toText(trr.endRow); } public RowRange(Text startRow, Text endRow) { this.startRow = startRow; this.endRow = endRow; } public Range toRange() { return new Range(startRow, false, endRow, true); } public TRowRange toThrift() { return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow)); } public Text getStartRow() { return startRow; } public Text getEndRow() { return endRow; } @Override public String toString() { return startRow + " " + endRow; } } |
data class | data class | t | t | t | 0 | 10658 | https://github.com/apache/accumulo/blob/f896c98c2356a52dfa2235d2cc02ae556ab17909/core/src/main/java/org/apache/accumulo/core/summary/Gatherer.java/#L617-L656 | 1 | 1301 | 10658 | minor | ||
| 3937 | YES I found bad smells The bad smells are: 1.Long method, 2.Magic number | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | Long method, 2Magic number | t | f | t | 2.Magic number | 0 | 10309 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 3937 | 10309 | major | |
| 1013 | { "message": "YES I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DataSourceLoginService extends AbstractLoginService { private static final Logger LOG = Log.getLogger(DataSourceLoginService.class); private String _jndiName = "javax.sql.DataSource/default"; private DataSource _datasource; private Server _server; private String _userTableName = "users"; private String _userTableKey = "id"; private String _userTableUserField = "username"; private String _userTablePasswordField = "pwd"; private String _roleTableName = "roles"; private String _roleTableKey = "id"; private String _roleTableRoleField = "role"; private String _userRoleTableName = "user_roles"; private String _userRoleTableUserKey = "user_id"; private String _userRoleTableRoleKey = "role_id"; private String _userSql; private String _roleSql; private boolean _createTables = false; /** * DBUser */ public class DBUserPrincipal extends UserPrincipal { private int _key; public DBUserPrincipal(String name, Credential credential, int key) { super(name, credential); _key = key; } public int getKey () { return _key; } } /* ------------------------------------------------------------ */ public DataSourceLoginService() { } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name) { setName(name); } /* ------------------------------------------------------------ */ public DataSourceLoginService(String name, IdentityService identityService) { setName(name); setIdentityService(identityService); } /* ------------------------------------------------------------ */ public void setJndiName (String jndi) { _jndiName = jndi; } /* ------------------------------------------------------------ */ public String getJndiName () { return _jndiName; } /* ------------------------------------------------------------ */ public void setServer (Server server) { _server=server; } /* ------------------------------------------------------------ */ public Server getServer() { return _server; } /* ------------------------------------------------------------ */ public void setCreateTables(boolean createTables) { _createTables = createTables; } /* ------------------------------------------------------------ */ public boolean getCreateTables() { return _createTables; } /* ------------------------------------------------------------ */ public void setUserTableName (String name) { _userTableName=name; } /* ------------------------------------------------------------ */ public String getUserTableName() { return _userTableName; } /* ------------------------------------------------------------ */ public String getUserTableKey() { return _userTableKey; } /* ------------------------------------------------------------ */ public void setUserTableKey(String tableKey) { _userTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getUserTableUserField() { return _userTableUserField; } /* ------------------------------------------------------------ */ public void setUserTableUserField(String tableUserField) { _userTableUserField = tableUserField; } /* ------------------------------------------------------------ */ public String getUserTablePasswordField() { return _userTablePasswordField; } /* ------------------------------------------------------------ */ public void setUserTablePasswordField(String tablePasswordField) { _userTablePasswordField = tablePasswordField; } /* ------------------------------------------------------------ */ public String getRoleTableName() { return _roleTableName; } /* ------------------------------------------------------------ */ public void setRoleTableName(String tableName) { _roleTableName = tableName; } /* ------------------------------------------------------------ */ public String getRoleTableKey() { return _roleTableKey; } /* ------------------------------------------------------------ */ public void setRoleTableKey(String tableKey) { _roleTableKey = tableKey; } /* ------------------------------------------------------------ */ public String getRoleTableRoleField() { return _roleTableRoleField; } /* ------------------------------------------------------------ */ public void setRoleTableRoleField(String tableRoleField) { _roleTableRoleField = tableRoleField; } /* ------------------------------------------------------------ */ public String getUserRoleTableName() { return _userRoleTableName; } /* ------------------------------------------------------------ */ public void setUserRoleTableName(String roleTableName) { _userRoleTableName = roleTableName; } /* ------------------------------------------------------------ */ public String getUserRoleTableUserKey() { return _userRoleTableUserKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableUserKey(String roleTableUserKey) { _userRoleTableUserKey = roleTableUserKey; } /* ------------------------------------------------------------ */ public String getUserRoleTableRoleKey() { return _userRoleTableRoleKey; } /* ------------------------------------------------------------ */ public void setUserRoleTableRoleKey(String roleTableRoleKey) { _userRoleTableRoleKey = roleTableRoleKey; } /* ------------------------------------------------------------ */ @Override public UserPrincipal loadUserInfo (String username) { try { try (Connection connection = getConnection(); PreparedStatement statement1 = connection.prepareStatement(_userSql)) { statement1.setObject(1, username); try (ResultSet rs1 = statement1.executeQuery()) { if (rs1.next()) { int key = rs1.getInt(_userTableKey); String credentials = rs1.getString(_userTablePasswordField); return new DBUserPrincipal(username, Credential.getCredential(credentials), key); } } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+username, e); } return null; } /* ------------------------------------------------------------ */ @Override public String[] loadRoleInfo (UserPrincipal user) { DBUserPrincipal dbuser = (DBUserPrincipal)user; try { try (Connection connection = getConnection(); PreparedStatement statement2 = connection.prepareStatement(_roleSql)) { List roles = new ArrayList(); statement2.setInt(1, dbuser.getKey()); try (ResultSet rs2 = statement2.executeQuery()) { while (rs2.next()) { roles.add(rs2.getString(_roleTableRoleField)); } return roles.toArray(new String[roles.size()]); } } } catch (NamingException e) { LOG.warn("No datasource for "+_jndiName, e); } catch (SQLException e) { LOG.warn("Problem loading user info for "+user.getName(), e); } return null; } /* ------------------------------------------------------------ */ /** * Lookup the datasource for the jndiName and formulate the * necessary sql query strings based on the configured table * and column names. * * @throws NamingException if unable to init jndi * @throws SQLException if unable to init database */ public void initDb() throws NamingException, SQLException { if (_datasource != null) return; @SuppressWarnings("unused") InitialContext ic = new InitialContext(); assert ic!=null; // TODO Should we try webapp scope too? // try finding the datasource in the Server scope if (_server != null) { try { _datasource = (DataSource)NamingEntryUtil.lookup(_server, _jndiName); } catch (NameNotFoundException e) { //next try the jvm scope } } //try finding the datasource in the jvm scope if (_datasource==null) { _datasource = (DataSource)NamingEntryUtil.lookup(null, _jndiName); } // set up the select statements based on the table and column names configured _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTableName + " where "+ _userTableUserField + " = ?"; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTableName + " r, " + _userRoleTableName + " u where u."+ _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey; prepareTables(); } /* ------------------------------------------------------------ */ /** * @throws NamingException * @throws SQLException */ private void prepareTables() throws NamingException, SQLException { if (_createTables) { boolean autocommit = true; Connection connection = getConnection(); try (Statement stmt = connection.createStatement()) { autocommit = connection.getAutoCommit(); connection.setAutoCommit(false); DatabaseMetaData metaData = connection.getMetaData(); //check if tables exist String tableName = (metaData.storesLowerCaseIdentifiers()? _userTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userTableName.toUpperCase(Locale.ENGLISH): _userTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user table default /* * create table _userTableName (_userTableKey integer, * _userTableUserField varchar(100) not null unique, * _userTablePasswordField varchar(20) not null, primary key(_userTableKey)); */ stmt.executeUpdate("create table "+_userTableName+ "("+_userTableKey+" integer,"+ _userTableUserField+" varchar(100) not null unique,"+ _userTablePasswordField+" varchar(20) not null, primary key("+_userTableKey+"))"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _roleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_roleTableName.toUpperCase(Locale.ENGLISH): _roleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //role table default /* * create table _roleTableName (_roleTableKey integer, * _roleTableRoleField varchar(100) not null unique, primary key(_roleTableKey)); */ String str = "create table "+_roleTableName+" ("+_roleTableKey+" integer, "+ _roleTableRoleField+" varchar(100) not null unique, primary key("+_roleTableKey+"))"; stmt.executeUpdate(str); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_roleTableName); } } tableName = (metaData.storesLowerCaseIdentifiers()? _userRoleTableName.toLowerCase(Locale.ENGLISH): (metaData.storesUpperCaseIdentifiers()?_userRoleTableName.toUpperCase(Locale.ENGLISH): _userRoleTableName)); try (ResultSet result = metaData.getTables(null, null, tableName, null)) { if (!result.next()) { //user-role table /* * create table _userRoleTableName (_userRoleTableUserKey integer, * _userRoleTableRoleKey integer, * primary key (_userRoleTableUserKey, _userRoleTableRoleKey)); * * create index idx_user_role on _userRoleTableName (_userRoleTableUserKey); */ stmt.executeUpdate("create table "+_userRoleTableName+" ("+_userRoleTableUserKey+" integer, "+ _userRoleTableRoleKey+" integer, "+ "primary key ("+_userRoleTableUserKey+", "+_userRoleTableRoleKey+"))"); stmt.executeUpdate("create index indx_user_role on "+_userRoleTableName+"("+_userRoleTableUserKey+")"); if (LOG.isDebugEnabled()) LOG.debug("Created table "+_userRoleTableName +" and index"); } } connection.commit(); } finally { try { connection.setAutoCommit(autocommit); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } finally { try { connection.close(); } catch (SQLException e) { if (LOG.isDebugEnabled()) LOG.debug("Prepare tables", e); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("createTables false"); } } /* ------------------------------------------------------------ */ /** * @return * @throws NamingException * @throws SQLException */ private Connection getConnection () throws NamingException, SQLException { initDb(); return _datasource.getConnection(); } } |
data class | long method, data class | t | t | t | long method | 0 | 9294 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-plus/src/main/java/org/eclipse/jetty/plus/security/DataSourceLoginService.java/#L52-L530 | 1 | 1013 | 9294 | minor | |
| 582 | YES I found bad smells the bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
feature envy | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 5787 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 582 | 5787 | major | ||
| 2124 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TextAndButtonSection extends Section { public TextAndButtonSection( String labelText, Composite parent, boolean isFormStyle ) { super( labelText, parent, isFormStyle ); } protected int width = -1; protected boolean fillText = false; protected TextPropertyDescriptor textField; public void createSection( ) { if ( selectList == null ) selectList = new ArrayList( ); getLabelControl( parent ); getTextControl( parent ); getButtonControl( parent ); getGridPlaceholder( parent ); } public void layout( ) { GridData gd = (GridData) textField.getControl( ).getLayoutData( ); if ( getLayoutNum( ) > 0 ) gd.horizontalSpan = getLayoutNum( ) - 2 - placeholder; else gd.horizontalSpan = ( (GridLayout) parent.getLayout( ) ).numColumns - 2 - placeholder; if ( width > -1 ) { gd.widthHint = width; gd.grabExcessHorizontalSpace = false; } else gd.grabExcessHorizontalSpace = fillText; gd = (GridData) button.getLayoutData( ); if ( buttonWidth > -1 ) { if ( !isComputeSize ) gd.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth ); else gd.widthHint = button.computeSize( -1, -1 ).x; } } public TextPropertyDescriptor getTextControl( ) { return textField; } protected TextPropertyDescriptor getTextControl( Composite parent ) { if ( textField == null ) { textField = DescriptorToolkit.createTextPropertyDescriptor( true ); if ( getProvider( ) != null ) textField.setDescriptorProvider( getProvider( ) ); textField.createControl( parent ); textField.getControl( ).setLayoutData( new GridData( ) ); textField.getControl( ).addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { textField = null; } } ); } else { checkParent( textField.getControl( ), parent ); } return textField; } protected Button button; public Button getButtonControl( ) { return button; } protected Button getButtonControl( Composite parent ) { if ( button == null ) { button = FormWidgetFactory.getInstance( ).createButton( parent, SWT.PUSH, isFormStyle ); button.setFont( parent.getFont( ) ); button.setLayoutData( new GridData( ) ); String text = getButtonText( ); if ( text != null ) { button.setText( text ); } text = getButtonTooltipText( ); if ( text != null ) { button.setToolTipText( text ); } button.addDisposeListener( new DisposeListener( ) { public void widgetDisposed( DisposeEvent event ) { button = null; } } ); if ( !selectList.isEmpty( ) ) button.addSelectionListener( (SelectionListener) selectList.get( 0 ) ); else { SelectionListener listener = new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { onClickButton( ); } }; selectList.add( listener ); } } else { checkParent( button, parent ); } return button; } private String buttonText; IDescriptorProvider provider; public IDescriptorProvider getProvider( ) { return provider; } public void setProvider( IDescriptorProvider provider ) { this.provider = provider; if ( textField != null ) textField.setDescriptorProvider( provider ); } protected List selectList = new ArrayList( ); /** * if use this method , you couldn't use the onClickButton method. */ public void addSelectionListener( SelectionListener listener ) { if ( !selectList.contains( listener ) ) { if ( !selectList.isEmpty( ) ) removeSelectionListener( (SelectionListener) selectList.get( 0 ) ); selectList.add( listener ); if ( button != null ) button.addSelectionListener( listener ); } } public void removeSelectionListener( SelectionListener listener ) { if ( selectList.contains( listener ) ) { selectList.remove( listener ); if ( button != null ) button.removeSelectionListener( listener ); } } protected void onClickButton( ) { }; public void forceFocus( ) { textField.getControl( ).forceFocus( ); } public void setInput( Object input ) { textField.setInput( input ); } public void load( ) { if ( textField != null && !textField.getControl( ).isDisposed( ) ) textField.load( ); if ( button != null && !button.isDisposed( ) ) button.setEnabled( !isReadOnly( ) ); } protected int buttonWidth = 60; public void setButtonWidth( int buttonWidth ) { this.buttonWidth = buttonWidth; if ( button != null ) { GridData data = new GridData( ); data.widthHint = Math.max( button.computeSize( -1, -1 ).x, buttonWidth );; data.grabExcessHorizontalSpace = false; button.setLayoutData( data ); } } protected boolean isComputeSize = false; public int getWidth( ) { return width; } public void setWidth( int width ) { this.width = width; } public int getButtonWidth( ) { return buttonWidth; } private String oldValue; public void setStringValue( String value ) { if ( textField != null ) { if ( value == null ) { value = "";//$NON-NLS-1$ } oldValue = textField.getText( ); if ( !oldValue.equals( value ) ) { textField.setText( value ); } } } public boolean isFillText( ) { return fillText; } public void setFillText( boolean fillText ) { this.fillText = fillText; } public void setHidden( boolean isHidden ) { if ( displayLabel != null ) WidgetUtil.setExcludeGridData( displayLabel, isHidden ); if ( textField != null ) textField.setHidden( isHidden ); if ( button != null ) WidgetUtil.setExcludeGridData( button, isHidden ); if ( placeholderLabel != null ) WidgetUtil.setExcludeGridData( placeholderLabel, isHidden ); } public void setVisible( boolean isVisible ) { if ( displayLabel != null ) displayLabel.setVisible( isVisible ); if ( textField != null ) textField.setVisible( isVisible ); if ( button != null ) button.setVisible( isVisible ); if ( placeholderLabel != null ) placeholderLabel.setVisible( isVisible ); } private String buttonTooltipText; public void setButtonTooltipText( String string ) { this.buttonTooltipText = string; if ( button != null ) button.setText( buttonTooltipText ); } public String getButtonText( ) { return buttonText; } public void setButtonText( String buttonText ) { this.buttonText = buttonText; if ( button != null ) button.setText( buttonText ); } public String getButtonTooltipText( ) { return buttonTooltipText; } public boolean buttonIsComputeSize( ) { return isComputeSize; } public void setButtonIsComputeSize( boolean isComputeSize ) { this.isComputeSize = isComputeSize; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 13216 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/section/TextAndButtonSection.java/#L23-L351 | 1 | 2124 | 13216 | major |
| 961 | YES, I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Dead code 4. Feature envy 5. Magic numbers | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long method2 Duplicate code3 Dead code4 Feature envy5 Magic numbers | t | f | t | 0 | 8569 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 2 | 961 | 8569 | minor | ||
| 1797 | {"message":"YES I found bad smells","bad smells are":["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
long method | long method | t | t | t | 0 | 12001 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 1 | 1797 | 12001 | major | ||
| 1666 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void addOutputContainerData() { @SuppressWarnings("resource") final VarCharVector fragmentIdVector = (VarCharVector) container.getValueAccessorById( VarCharVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Fragment")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(fragmentIdVector, 1, 50); @SuppressWarnings("resource") final BigIntVector summaryVector = (BigIntVector) container.getValueAccessorById(BigIntVector.class, container.getValueVectorId(SchemaPath.getSimplePath("Number of records written")).getFieldIds()) .getValueVector(); AllocationHelper.allocate(summaryVector, 1, 8); fragmentIdVector.getMutator().setSafe(0, fragmentUniqueId.getBytes()); fragmentIdVector.getMutator().setValueCount(1); summaryVector.getMutator().setSafe(0, counter); summaryVector.getMutator().setValueCount(1); container.setRecordCount(1); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 11623 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WriterRecordBatch.java/#L138-L156 | 2 | 1666 | 11623 | minor | ||
| 575 | { "output": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private EntityCollection createETStreamOnComplexProp(Edm edm, OData odata) { EntityCollection entityCollection = new EntityCollection(); Link readLink = new Link(); readLink.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink.setHref("readLink"); Entity entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("darkturquoise"))); readLink.setInlineEntity(entity); Link readLink1 = new Link(); readLink1.setRel(Constants.NS_MEDIA_READ_LINK_REL); readLink1.setHref("readLink"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("darkturquoise"))); readLink1.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE)) .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, readLink1)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, readLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); Link editLink = new Link(); editLink.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink.setHref("http://mediaserver:1234/editLink"); editLink.setMediaETag("eTag"); editLink.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyStream", createImage("royalblue"))); editLink.setInlineEntity(entity); Link editLink2 = new Link(); editLink2.setRel(Constants.NS_MEDIA_EDIT_LINK_REL); editLink2.setHref("http://mediaserver:1234/editLink"); editLink2.setMediaETag("eTag"); editLink2.setType("image/jpeg"); entity = new Entity(); entity.addProperty(createPrimitive("PropertyEntityStream", createImage("royalblue"))); editLink2.setInlineEntity(entity); entityCollection.getEntities().add(new Entity() .addProperty(createPrimitive("PropertyInt16", (short) 7)) .addProperty(createPrimitive("PropertyInt32", (Integer) 10)) .addProperty(new Property(null, "PropertyEntityStream", ValueType.PRIMITIVE, editLink2)) .addProperty(createComplex("PropertyCompWithStream", ComplexTypeProvider.nameCTWithStreamProp.getFullQualifiedNameAsString(), new Property(null, "PropertyStream", ValueType.PRIMITIVE, editLink), createComplex("PropertyComp", ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(), createPrimitive("PropertyInt16", (short) 333), createPrimitive("PropertyString", "TEST123"))))); setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETStreamOnComplexProp)); createEntityId(edm, odata, "ESStreamOnComplexProp", entityCollection); createOperations("ESStreamOnComplexProp", entityCollection, EntityTypeProvider.nameETStreamOnComplexProp); return entityCollection; } |
long method | data class, long method | t | t | t | data class | 0 | 5777 | https://github.com/apache/olingo-odata4/blob/f344a3c565b6a67233de1d1169104a728136e7a3/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/data/DataCreator.java/#L158-L221 | 1 | 575 | 5777 | critical | |
| 2381 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Magic numbers 5. Inconsistent naming conventions 6. Multiple levels of indentation 7. Unnecessary comments 8. Poor exception handling 9. Unnecessary synchronization 10. Use of best effort instead of handling errors properly. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | Long method2 Feature envy3 Duplicate code4 Magic numbers5 Inconsistent naming conventions6 Multiple levels of indentation7 Unnecessary comments8 Poor exception handling 9 Unnecessary synchronization | t | f | t | 0 | 14338 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 2 | 2381 | 14338 | minor | ||
| 2284 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class BindableSolrParameter { private final int index; private final Object value; private float boost; public BindableSolrParameter(int index, Object value) { super(); this.index = index; this.value = value; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } public int getIndex() { return index; } public Object getValue() { return value; } } |
data class | data class | t | t | t | 0 | 13857 | https://github.com/spring-projects/spring-data-solr/blob/6db215cf28337895ec40ed28082fa895846680bb/src/main/java/org/springframework/data/solr/repository/query/BindableSolrParameter.java/#L24-L52 | 1 | 2284 | 13857 | major | ||
| 5176 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @InterfaceAudience.Private @Metrics(context="metricssystem") public class MetricsSystemImpl extends MetricsSystem implements MetricsSource { static final Log LOG = LogFactory.getLog(MetricsSystemImpl.class); static final String MS_NAME = "MetricsSystem"; static final String MS_STATS_NAME = MS_NAME +",sub=Stats"; static final String MS_STATS_DESC = "Metrics system metrics"; static final String MS_CONTROL_NAME = MS_NAME +",sub=Control"; static final String MS_INIT_MODE_KEY = "hadoop.metrics.init.mode"; enum InitMode { NORMAL, STANDBY } private final Map sources; private final Map allSources; private final Map sinks; private final Map allSinks; private final List callbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private int period; // seconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.info(this.prefix +" metrics system started (again)"); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.info(prefix +" metrics system started in standby mode"); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.info(prefix +" metrics system started"); for (Callback cb : callbacks) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.info(prefix +" metrics system stopped (again)"); return; } for (Callback cb : callbacks) cb.preStop(); LOG.info("Stopping "+ prefix +" metrics system..."); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.info(prefix +" metrics system stopped."); for (Callback cb : callbacks) cb.postStop(); } @Override public synchronized T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { LOG.warn("Sink "+ name +" already exists!"); return sink; } allSinks.put(name, sink); if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); sa.start(); LOG.info("Registered sink "+ name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) Proxy.newProxyInstance( callback.getClass().getClassLoader(), new Class[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback "+ method.getName(), e); } return null; } })); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.save(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period * 1000; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn(e); } } }, millis, millis); LOG.info("Scheduled snapshot period at "+ period +" second(s)."); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.now(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.now() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.now(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.now() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); int confPeriod = 0; for (Entry entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); confPeriod = confPeriod == 0 ? sinkPeriod : ArithmeticUtils.gcd(confPeriod, sinkPeriod); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } period = confPeriod > 0 ? confPeriod : config.getInt(PERIOD_KEY, PERIOD_DEFAULT); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT), conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.info(prefix +" metrics system shutdown complete."); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf((m2 == null ? InitMode.NORMAL.name() : m2) .toUpperCase(Locale.US)); } } |
blob | blob, long method | t | t | t | long method | 0 | 14479 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java/#L69-L601 | 1 | 5176 | 14479 | major | |
| 2361 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings( "raw" ) private static void simpleGenericNameOf( StringBuilder sb, Type type ) { if( type instanceof Class ) { sb.append( ( (Class) type ).getSimpleName() ); } else if( type instanceof ParameterizedType ) { ParameterizedType pt = (ParameterizedType) type; simpleGenericNameOf( sb, pt.getRawType() ); sb.append( "<" ); boolean atLeastOne = false; for( Type typeArgument : pt.getActualTypeArguments() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } sb.append( ">" ); } else if( type instanceof GenericArrayType ) { GenericArrayType gat = (GenericArrayType) type; simpleGenericNameOf( sb, gat.getGenericComponentType() ); sb.append( "[]" ); } else if( type instanceof TypeVariable ) { TypeVariable tv = (TypeVariable) type; sb.append( tv.getName() ); } else if( type instanceof WildcardType ) { WildcardType wt = (WildcardType) type; sb.append( "? extends " ); boolean atLeastOne = false; for( Type typeArgument : wt.getUpperBounds() ) { if( atLeastOne ) { sb.append( ", " ); } simpleGenericNameOf( sb, typeArgument ); atLeastOne = true; } } else { throw new IllegalArgumentException( "Don't know how to deal with type:" + type ); } } |
long method | long method | t | t | t | 0 | 14251 | https://github.com/apache/attic-polygene-java/blob/031beef870302a0bd01bd5895ce849e00f2d5d5b/core/api/src/main/java/org/apache/polygene/api/util/Classes.java/#L288-L342 | 1 | 2361 | 14251 | major | ||
| 1583 | Yes I found bad smells: 1. Long method, 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static Class findProviderClass(String className, ClassLoader cl, boolean doFallback) throws ClassNotFoundException, ConfigurationError { //throw security exception if the calling thread is not allowed to access the //class. Restrict the access to the package classes as specified in java.security policy. SecurityManager security = System.getSecurityManager(); try{ if (security != null){ final int lastDot = className.lastIndexOf('.'); String packageName = className; if (lastDot != -1) packageName = className.substring(0, lastDot); security.checkPackageAccess(packageName); } }catch(SecurityException e){ throw e; } Class providerClass; if (cl == null) { // XXX Use the bootstrap ClassLoader. There is no way to // load a class using the bootstrap ClassLoader that works // in both JDK 1.1 and Java 2. However, this should still // work b/c the following should be true: // // (cl == null) iff current ClassLoader == null // // Thus Class.forName(String) will use the current // ClassLoader which will be the bootstrap ClassLoader. providerClass = Class.forName(className); } else { try { providerClass = cl.loadClass(className); } catch (ClassNotFoundException x) { if (doFallback) { // Fall back to current classloader ClassLoader current = ObjectFactory.class.getClassLoader(); if (current == null) { providerClass = Class.forName(className); } else if (cl != current) { cl = current; providerClass = cl.loadClass(className); } else { throw x; } } else { throw x; } } } return providerClass; } |
long method | Long method, 2 Feature envy, 3 Duplicate code, 4 Complex conditional logic (if statements nested within other if statements), 5 Misleading comments (commented out code that is not being used), 6 Manual exception handling rather than using a try-catch block | t | f | t | 2. Feature envy, 3. Duplicate code, 4. Complex conditional logic (if statements nested within other if statements), 5. Misleading comments (commented out code that is not being used), 6. Manual exception handling rather than using a try-catch block. | 0 | 11365 | https://github.com/apache/servicemix-bundles/blob/5f2c7727f71c167997947ad4604f9b8200952af2/xalan-2.7.2/src/main/java/org/apache/xalan/xsltc/runtime/ObjectFactory.java/#L477-L529 | 2 | 1583 | 11365 | minor | |
| 560 | { "message": "YES, I found bad smells", "bad smells are": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class FakeErrorBoxWidget implements IErrorBox { /** * Boolean to signify if a listener was registered. */ private boolean observed; /** * Boolean to store the display state. */ private boolean displayed; /** * The error message. */ private String errorMsg = null; /** * This operation returns true if the display operation is called for the FakeErrorBoxWidget. * @return True if the widget was displayed, false if not. */ public boolean widgetDisplayed() { return this.displayed; } /** * This operation implements display() from UIWidget with a simple pass through that makes whether or not the method was called. Nothing is drawn on the screen. */ @Override public void display() { this.displayed = true; return; } /** * (non-Javadoc) * @see IErrorBox#setErrorString(String error) */ @Override public void setErrorString(String error) { // Set the error message errorMsg = error; return; } /** * (non-Javadoc) * @see IErrorBox#getErrorString() */ @Override public String getErrorString() { // Return the error message return errorMsg; } } |
data class | 1. data class | t | t | f | data class | 0 | 5653 | https://github.com/eclipse/ice/blob/3f6e0265f5b476ff90a660397ce83992944142c4/org.eclipse.ice.tests.client/src/org/eclipse/ice/tests/client/FakeErrorBoxWidget.java/#L21-L82 | 1 | 560 | 5653 | major | |
| 2154 | YES, I found bad smells the bad smells are:1. Long method, 2. Primitive obsession, 3. Duplicate code, 4. Magic number (0), 5. Feature envy, 6. Inappropriate commenting, 7. Inconsistent formatting, 8. Data clumps, 9. Missing abstraction, 10. Inefficient looping (for loop instead of foreach), 11. Inappropriate use of List (instead of Set or Map). | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
feature envy | Long method, 2 Primitive obsession, 3 Duplicate code, 4 Magic number (0), 5 Feature envy, 6 Inappropriate commenting, 7 Inconsistent formatting, 8 Data clumps, 9 Missing abstraction, | t | f | t | . Long method, 2. Primitive obsession, 3. Duplicate code, 4. Magic number (0), 6. Inappropriate commenting, 7. Inconsistent formatting, 8. Data clumps, 9. Missing abstraction, | 0 | 13296 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 2 | 2154 | 13296 | minor | |
| 5526 | { "response": "YES I found bad smells", "details": "the bad smells are:", "bad_smells": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void asJson(OutputStream out, Map data) throws HiveException { try { new ObjectMapper().writeValue(out, data); } catch (IOException e) { throw new HiveException("Unable to convert to json", e); } } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 5595 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/JsonMetaDataFormatter.java/#L76-L84 | 2 | 5526 | 5595 | minor | |
| 4604 | { "message": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name = "pagedResult") @XmlType public class PagedResult implements Serializable { private static final long serialVersionUID = 3472875885259250934L; private URI prev; private URI next; private final List result = new ArrayList<>(); private int page; private int size; private int totalCount; public URI getPrev() { return prev; } public void setPrev(final URI prev) { this.prev = prev; } public URI getNext() { return next; } public void setNext(final URI next) { this.next = next; } @XmlElementWrapper(name = "result") @XmlElement(name = "item") @JsonProperty("result") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public List getResult() { return result; } public int getPage() { return page; } public void setPage(final int page) { this.page = page; } public int getSize() { return size; } public void setSize(final int size) { this.size = size; } public int getTotalCount() { return totalCount; } public void setTotalCount(final int totalCount) { this.totalCount = totalCount; } @Override public int hashCode() { return new HashCodeBuilder(). append(prev). append(next). append(result). append(page). append(size). append(totalCount). build(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") final PagedResult other = (PagedResult) obj; return new EqualsBuilder(). append(prev, other.prev). append(next, other.next). append(result, other.result). append(page, other.page). append(size, other.size). append(totalCount, other.totalCount). build(); } } |
data class | blob, data class | t | t | t | blob | 0 | 12251 | https://github.com/apache/syncope/blob/114c412afbfba24ffb4fbc804e5308a823a16a78/common/idrepo/lib/src/main/java/org/apache/syncope/common/lib/to/PagedResult.java/#L35-L135 | 1 | 4604 | 12251 | minor | |
| 2499 | YES, I found bad smells the bad smells are: 1.Long method, 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, 10.Unnecessary null check, 11.Switch statement. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void onTrigger(final ProcessContext context, final ProcessSession session) { List flowFiles = session.get(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger()); if (flowFiles == null || flowFiles.size() == 0) { return; } Map keysToFlowFileMap = new HashMap<>(); final String table = context.getProperty(TABLE).evaluateAttributeExpressions().getValue(); final String hashKeyName = context.getProperty(HASH_KEY_NAME).evaluateAttributeExpressions().getValue(); final String hashKeyValueType = context.getProperty(HASH_KEY_VALUE_TYPE).getValue(); final String rangeKeyName = context.getProperty(RANGE_KEY_NAME).evaluateAttributeExpressions().getValue(); final String rangeKeyValueType = context.getProperty(RANGE_KEY_VALUE_TYPE).getValue(); final String jsonDocument = context.getProperty(JSON_DOCUMENT).evaluateAttributeExpressions().getValue(); final String charset = context.getProperty(DOCUMENT_CHARSET).evaluateAttributeExpressions().getValue(); TableWriteItems tableWriteItems = new TableWriteItems(table); for (FlowFile flowFile : flowFiles) { final Object hashKeyValue = getValue(context, HASH_KEY_VALUE_TYPE, HASH_KEY_VALUE, flowFile); final Object rangeKeyValue = getValue(context, RANGE_KEY_VALUE_TYPE, RANGE_KEY_VALUE, flowFile); if (!isHashKeyValueConsistent(hashKeyName, hashKeyValue, session, flowFile)) { continue; } if (!isRangeKeyValueConsistent(rangeKeyName, rangeKeyValue, session, flowFile)) { continue; } if (!isDataValid(flowFile, jsonDocument)) { flowFile = session.putAttribute(flowFile, AWS_DYNAMO_DB_ITEM_SIZE_ERROR, "Max size of item + attribute should be 400kb but was " + flowFile.getSize() + jsonDocument.length()); session.transfer(flowFile, REL_FAILURE); continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); session.exportTo(flowFile, baos); try { if (rangeKeyValue == null || StringUtils.isBlank(rangeKeyValue.toString())) { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } else { tableWriteItems.addItemToPut(new Item().withKeyComponent(hashKeyName, hashKeyValue) .withKeyComponent(rangeKeyName, rangeKeyValue) .withJSON(jsonDocument, IOUtils.toString(baos.toByteArray(), charset))); } } catch (IOException ioe) { getLogger().error("IOException while creating put item : " + ioe.getMessage()); flowFile = session.putAttribute(flowFile, DYNAMODB_ITEM_IO_ERROR, ioe.getMessage()); session.transfer(flowFile, REL_FAILURE); } keysToFlowFileMap.put(new ItemKeys(hashKeyValue, rangeKeyValue), flowFile); } if (keysToFlowFileMap.isEmpty()) { return; } final DynamoDB dynamoDB = getDynamoDB(); try { BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems); handleUnprocessedItems(session, keysToFlowFileMap, table, hashKeyName, hashKeyValueType, rangeKeyName, rangeKeyValueType, outcome); // Handle any remaining flowfiles for (FlowFile flowFile : keysToFlowFileMap.values()) { getLogger().debug("Successful posted items to dynamodb : " + table); session.transfer(flowFile, REL_SUCCESS); } } catch (AmazonServiceException exception) { getLogger().error("Could not process flowFiles due to service exception : " + exception.getMessage()); List failedFlowFiles = processServiceException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (AmazonClientException exception) { getLogger().error("Could not process flowFiles due to client exception : " + exception.getMessage()); List failedFlowFiles = processClientException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } catch (Exception exception) { getLogger().error("Could not process flowFiles due to exception : " + exception.getMessage()); List failedFlowFiles = processException(session, flowFiles, exception); session.transfer(failedFlowFiles, REL_FAILURE); } } |
long method | Long method, 2Unnecessary variable, 3Magic number, 4Duplicate code, 5Inconsistent naming conventions, 6Feature envy, 7Inappropriate comments, 8Unnecessary nesting, 9Exception handling, | t | f | t | 2.Unnecessary variable, 3.Magic number, 4.Duplicate code, 5.Inconsistent naming conventions, 6.Feature envy, 7.Inappropriate comments, 8.Unnecessary nesting, 9.Exception handling, | 0 | 14652 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/dynamodb/PutDynamoDB.java/#L100-L188 | 2 | 2499 | 14652 | critical | |
| 850 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement(name="mqtt") @XmlAccessorType(XmlAccessType.FIELD) public class MqttDTO extends ProtocolDTO { @XmlAttribute(name="max_message_length") public Integer max_message_length; @XmlElementRef public List protocol_filters = new ArrayList(); @XmlAttribute(name="queue_prefix") public String queue_prefix; @XmlAttribute(name="path_separator") public String path_separator; @XmlAttribute(name="any_child_wildcard") public String any_child_wildcard; @XmlAttribute(name="any_descendant_wildcard") public String any_descendant_wildcard; @XmlAttribute(name="regex_wildcard_start") public String regex_wildcard_start; @XmlAttribute(name="regex_wildcard_end") public String regex_wildcard_end; @XmlAttribute(name="part_pattern") public String part_pattern; @XmlAttribute(name="die_delay") public Long die_delay; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MqttDTO mqttDTO = (MqttDTO) o; if (any_child_wildcard != null ? !any_child_wildcard.equals(mqttDTO.any_child_wildcard) : mqttDTO.any_child_wildcard != null) return false; if (any_descendant_wildcard != null ? !any_descendant_wildcard.equals(mqttDTO.any_descendant_wildcard) : mqttDTO.any_descendant_wildcard != null) return false; if (max_message_length != null ? !max_message_length.equals(mqttDTO.max_message_length) : mqttDTO.max_message_length != null) return false; if (path_separator != null ? !path_separator.equals(mqttDTO.path_separator) : mqttDTO.path_separator != null) return false; if (protocol_filters != null ? !protocol_filters.equals(mqttDTO.protocol_filters) : mqttDTO.protocol_filters != null) return false; if (queue_prefix != null ? !queue_prefix.equals(mqttDTO.queue_prefix) : mqttDTO.queue_prefix != null) return false; if (regex_wildcard_end != null ? !regex_wildcard_end.equals(mqttDTO.regex_wildcard_end) : mqttDTO.regex_wildcard_end != null) return false; if (regex_wildcard_start != null ? !regex_wildcard_start.equals(mqttDTO.regex_wildcard_start) : mqttDTO.regex_wildcard_start != null) return false; if (part_pattern != null ? !part_pattern.equals(mqttDTO.part_pattern) : mqttDTO.part_pattern != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (max_message_length != null ? max_message_length.hashCode() : 0); result = 31 * result + (protocol_filters != null ? protocol_filters.hashCode() : 0); result = 31 * result + (queue_prefix != null ? queue_prefix.hashCode() : 0); result = 31 * result + (part_pattern != null ? part_pattern.hashCode() : 0); result = 31 * result + (path_separator != null ? path_separator.hashCode() : 0); result = 31 * result + (any_child_wildcard != null ? any_child_wildcard.hashCode() : 0); result = 31 * result + (any_descendant_wildcard != null ? any_descendant_wildcard.hashCode() : 0); result = 31 * result + (regex_wildcard_start != null ? regex_wildcard_start.hashCode() : 0); result = 31 * result + (regex_wildcard_end != null ? regex_wildcard_end.hashCode() : 0); return result; } } |
data class | data class | t | t | t | 0 | 7851 | https://github.com/apache/activemq-apollo/blob/8e4b134b2a5d3576aa62cd8df9905a9fe2eba2d0/apollo-mqtt/src/main/java/org/apache/activemq/apollo/mqtt/dto/MqttDTO.java/#L31-L109 | 1 | 850 | 7851 | critical | ||
| 3960 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private class ClientSelectDeleteMutationPlan implements MutationPlan { private final StatementContext context; private final TableRef targetTableRef; private final QueryPlan dataPlan; private final QueryPlan bestPlan; private final boolean hasPreOrPostProcessing; private final DeletingParallelIteratorFactory parallelIteratorFactory; private final List otherTableRefs; private final TableRef projectedTableRef; private final int maxSize; private final int maxSizeBytes; private final PhoenixConnection connection; public ClientSelectDeleteMutationPlan(TableRef targetTableRef, QueryPlan dataPlan, QueryPlan bestPlan, boolean hasPreOrPostProcessing, DeletingParallelIteratorFactory parallelIteratorFactory, List otherTableRefs, TableRef projectedTableRef, int maxSize, int maxSizeBytes, PhoenixConnection connection) { this.context = bestPlan.getContext(); this.targetTableRef = targetTableRef; this.dataPlan = dataPlan; this.bestPlan = bestPlan; this.hasPreOrPostProcessing = hasPreOrPostProcessing; this.parallelIteratorFactory = parallelIteratorFactory; this.otherTableRefs = otherTableRefs; this.projectedTableRef = projectedTableRef; this.maxSize = maxSize; this.maxSizeBytes = maxSizeBytes; this.connection = connection; } @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public StatementContext getContext() { return context; } @Override public TableRef getTargetRef() { return targetTableRef; } @Override public Set getSourceRefs() { return dataPlan.getSourceRefs(); } @Override public Operation getOperation() { return operation; } @Override public MutationState execute() throws SQLException { ResultIterator iterator = bestPlan.iterator(); try { // If we're not doing any pre or post processing, we can produce the delete mutations directly // in the parallel threads executed for the scan if (!hasPreOrPostProcessing) { Tuple tuple; long totalRowCount = 0; if (parallelIteratorFactory != null) { parallelIteratorFactory.setQueryPlan(bestPlan); parallelIteratorFactory.setOtherTableRefs(otherTableRefs); parallelIteratorFactory.setProjectedTableRef(projectedTableRef); } while ((tuple=iterator.next()) != null) {// Runs query Cell kv = tuple.getValue(0); totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault()); } // Return total number of rows that have been deleted from the table. In the case of auto commit being off // the mutations will all be in the mutation state of the current connection. We need to divide by the // total number of tables we updated as otherwise the client will get an inflated result. int totalTablesUpdateClientSide = 1; // data table is always updated PTable bestTable = bestPlan.getTableRef().getTable(); // global immutable tables are also updated client side (but don't double count the data table) if (bestPlan != dataPlan && isMaintainedOnClient(bestTable)) { totalTablesUpdateClientSide++; } for (TableRef otherTableRef : otherTableRefs) { PTable otherTable = otherTableRef.getTable(); // Don't double count the data table here (which morphs when it becomes a projected table, hence this check) if (projectedTableRef != otherTableRef && isMaintainedOnClient(otherTable)) { totalTablesUpdateClientSide++; } } MutationState state = new MutationState(maxSize, maxSizeBytes, connection, totalRowCount/totalTablesUpdateClientSide); // set the read metrics accumulated in the parent context so that it can be published when the mutations are committed. state.setReadMetricQueue(context.getReadMetricsQueue()); return state; } else { // Otherwise, we have to execute the query and produce the delete mutations in the single thread // producing the query results. return deleteRows(context, iterator, bestPlan, projectedTableRef, otherTableRefs); } } finally { iterator.close(); } } @Override public ExplainPlan getExplainPlan() throws SQLException { List queryPlanSteps = bestPlan.getExplainPlan().getPlanSteps(); List planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1); planSteps.add("DELETE ROWS"); planSteps.addAll(queryPlanSteps); return new ExplainPlan(planSteps); } @Override public Long getEstimatedRowsToScan() throws SQLException { return bestPlan.getEstimatedRowsToScan(); } @Override public Long getEstimatedBytesToScan() throws SQLException { return bestPlan.getEstimatedBytesToScan(); } @Override public Long getEstimateInfoTimestamp() throws SQLException { return bestPlan.getEstimateInfoTimestamp(); } @Override public QueryPlan getQueryPlan() { return bestPlan; } } |
data class | long method, data class | t | t | t | long method | 0 | 10368 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java/#L844-L978 | 1 | 3960 | 10368 | critical | |
| 2658 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void read(org.apache.thrift.protocol.TProtocol iprot, WMTrigger struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // RESOURCE_PLAN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourcePlanName = iprot.readString(); struct.setResourcePlanNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // TRIGGER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerName = iprot.readString(); struct.setTriggerNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // TRIGGER_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.triggerExpression = iprot.readString(); struct.setTriggerExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // ACTION_EXPRESSION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.actionExpression = iprot.readString(); struct.setActionExpressionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // IS_IN_UNMANAGED if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.isInUnmanaged = iprot.readBool(); struct.setIsInUnmanagedIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // NS if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.ns = iprot.readString(); struct.setNsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 15186 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/WMTrigger.java/#L733-L798 | 2 | 2658 | 15186 | major | ||
| 1461 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected float removeInstanceTime(InstanceTime time, boolean isBegin) { // Trace.enter(this, "removeInstanceTime", new Object[] { time, new Boolean(isBegin) } ); try { hasPropagated = true; List instanceTimes = isBegin ? beginInstanceTimes : endInstanceTimes; int index = Collections.binarySearch(instanceTimes, time); for (int i = index; i >= 0; i--) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } int len = instanceTimes.size(); for (int i = index + 1; i < len; i++) { InstanceTime it = (InstanceTime) instanceTimes.get(i); if (it == time) { instanceTimes.remove(i); break; } if (it.compareTo(time) != 0) { break; } } shouldUpdateCurrentInterval = true; float ret; if (root.isSampling() && !isSampling) { ret = sampleAt(root.getCurrentTime(), root.isHyperlinking()); } else { ret = Float.POSITIVE_INFINITY; } hasPropagated = false; root.currentIntervalWillUpdate(); return ret; // } finally { Trace.exit(); } } |
long method | long method | t | t | t | 0 | 11023 | https://github.com/apache/batik/blob/8b9b758641a11c43c4e9493386268fa0dc5c7efb/batik-anim/src/main/java/org/apache/batik/anim/timing/TimedElement.java/#L306-L343 | 1 | 1461 | 11023 | minor | ||
| 4807 | { "message": "YES I found bad smells", "the bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class AbstractPmdReport extends AbstractMavenReport { /** * The output directory for the intermediate XML report. */ @Parameter( property = "project.build.directory", required = true ) protected File targetDirectory; /** * The output directory for the final HTML report. Note that this parameter is only evaluated if the goal is run * directly from the command line or during the default lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is used instead. */ @Parameter( property = "project.reporting.outputDirectory", required = true ) protected File outputDirectory; /** * Site rendering component for generating the HTML report. */ @Component private Renderer siteRenderer; /** * The project to analyse. */ @Parameter( defaultValue = "${project}", readonly = true, required = true ) protected MavenProject project; /** * Set the output format type, in addition to the HTML report. Must be one of: "none", "csv", "xml", "txt" or the * full class name of the PMD renderer to use. See the net.sourceforge.pmd.renderers package javadoc for available * renderers. XML is required if the pmd:check goal is being used. */ @Parameter( property = "format", defaultValue = "xml" ) protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ @Parameter( property = "linkXRef", defaultValue = "true" ) private boolean linkXRef; /** * Location of the Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) private File xrefLocation; /** * Location of the Test Xrefs to link to. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) private File xrefTestLocation; /** * A list of files to exclude from checking. Can contain Ant-style wildcards and double wildcards. Note that these * exclusion patterns only operate on the path of a source file relative to its source root directory. In other * words, files are excluded based on their package and/or class name. If you want to exclude entire source root * directories, use the parameter excludeRoots instead. * * @since 2.2 */ @Parameter private List excludes; /** * A list of files to include from checking. Can contain Ant-style wildcards and double wildcards. Defaults to * **\/*.java. * * @since 2.2 */ @Parameter private List includes; /** * Specifies the location of the source directories to be used for PMD. * Defaults to project.compileSourceRoots. * @since 3.7 */ @Parameter( defaultValue = "${project.compileSourceRoots}" ) private List compileSourceRoots; /** * The directories containing the test-sources to be used for PMD. * Defaults to project.testCompileSourceRoots * @since 3.7 */ @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) private List testSourceRoots; /** * The project source directories that should be excluded. * * @since 2.2 */ @Parameter private File[] excludeRoots; /** * Run PMD on the tests. * * @since 2.2 */ @Parameter( defaultValue = "false" ) protected boolean includeTests; /** * Whether to build an aggregated report at the root, or build individual reports. * * @since 2.2 */ @Parameter( property = "aggregate", defaultValue = "false" ) protected boolean aggregate; /** * The file encoding to use when reading the Java sources. * * @since 2.3 */ @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) private String sourceEncoding; /** * The file encoding when writing non-HTML reports. * * @since 2.5 */ @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) private String outputEncoding; /** * The projects in the reactor for aggregation report. */ @Parameter( property = "reactorProjects", readonly = true ) protected List reactorProjects; /** * Whether to include the xml files generated by PMD/CPD in the site. * * @since 3.0 */ @Parameter( defaultValue = "false" ) protected boolean includeXmlInSite; /** * Skip the PMD/CPD report generation if there are no violations or duplications found. Defaults to * true. * * @since 3.1 */ @Parameter( defaultValue = "true" ) protected boolean skipEmptyReport; /** * File that lists classes and rules to be excluded from failures. * For PMD, this is a properties file. For CPD, this * is a text file that contains comma-separated lists of classes * that are allowed to duplicate. * * @since 3.7 */ @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) protected String excludeFromFailureFile; /** The files that are being analyzed. */ protected Map filesToProcess; /** * {@inheritDoc} */ @Override protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ @Override protected Renderer getSiteRenderer() { return siteRenderer; } protected String constructXRefLocation( boolean test ) { String location = null; if ( linkXRef ) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); if ( StringUtils.isEmpty( relativePath ) ) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); if ( xrefLoc.exists() ) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; } else { // Not yet generated - check if the report is on its way @SuppressWarnings( "unchecked" ) List reportPlugins = project.getReportPlugins(); for ( ReportPlugin plugin : reportPlugins ) { String artifactId = plugin.getArtifactId(); if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) { location = relativePath; } } } if ( location == null ) { getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); } } return location; } /** * Convenience method to get the list of files where the PMD tool will be executed * * @return a List of the files where the PMD tool will be executed * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ protected Map getFilesToProcess() throws IOException { if ( aggregate && !project.isExecutionRoot() ) { return Collections.emptyMap(); } if ( excludeRoots == null ) { excludeRoots = new File[0]; } Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); for ( File file : excludeRoots ) { if ( file.isDirectory() ) { excludeRootFiles.add( file ); } } List directories = new ArrayList<>(); if ( null == compileSourceRoots ) { compileSourceRoots = project.getCompileSourceRoots(); } if ( compileSourceRoots != null ) { for ( String root : compileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); } } } if ( null == testSourceRoots ) { testSourceRoots = project.getTestCompileSourceRoots(); } if ( includeTests ) { if ( testSourceRoots != null ) { for ( String root : testSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( project, sroot, testXref ) ); } } } } if ( aggregate ) { for ( MavenProject localProject : reactorProjects ) { @SuppressWarnings( "unchecked" ) List localCompileSourceRoots = localProject.getCompileSourceRoots(); for ( String root : localCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String sourceXref = constructXRefLocation( false ); directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); } } if ( includeTests ) { @SuppressWarnings( "unchecked" ) List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); for ( String root : localTestCompileSourceRoots ) { File sroot = new File( root ); if ( sroot.exists() ) { String testXref = constructXRefLocation( true ); directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); } } } } } String excluding = getExcludes(); getLog().debug( "Exclusions: " + excluding ); String including = getIncludes(); getLog().debug( "Inclusions: " + including ); Map files = new TreeMap<>(); for ( PmdFileInfo finfo : directories ) { getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); File sourceDirectory = finfo.getSourceDirectory(); if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) { List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); for ( File newfile : newfiles ) { files.put( newfile.getCanonicalFile(), finfo ); } } } return files; } private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) { boolean returnVal = false; for ( File excludeDir : excludeRootFiles ) { try { if ( sourceDirectoryToCheck.getCanonicalPath().startsWith( excludeDir.getCanonicalPath() ) ) { getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() + " has been excluded as it matches excludeRoot " + excludeDir.getAbsolutePath() ); returnVal = true; break; } } catch ( IOException e ) { getLog().warn( "Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e ); } } return returnVal; } /** * Gets the comma separated list of effective include patterns. * * @return The comma separated list of effective include patterns, never null. */ private String getIncludes() { Collection patterns = new LinkedHashSet<>(); if ( includes != null ) { patterns.addAll( includes ); } if ( patterns.isEmpty() ) { patterns.add( "**/*.java" ); } return StringUtils.join( patterns.iterator(), "," ); } /** * Gets the comma separated list of effective exclude patterns. * * @return The comma separated list of effective exclude patterns, never null. */ private String getExcludes() { Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); if ( excludes != null ) { patterns.addAll( excludes ); } return StringUtils.join( patterns.iterator(), "," ); } protected boolean isHtml() { return "html".equals( format ); } protected boolean isXml() { return "xml".equals( format ); } /** * {@inheritDoc} */ @Override public boolean canGenerateReport() { if ( aggregate && !project.isExecutionRoot() ) { return false; } if ( "pom".equals( project.getPackaging() ) && !aggregate ) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures if ( isXml() ) { return true; } try { filesToProcess = getFilesToProcess(); if ( filesToProcess.isEmpty() ) { return false; } } catch ( IOException e ) { getLog().error( e ); } return true; } /** * {@inheritDoc} */ @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } protected String getSourceEncoding() { return sourceEncoding; } /** * Gets the effective reporting output files encoding. * * @return The effective reporting output file encoding, never null. * @since 2.5 */ protected String getOutputEncoding() { return ( outputEncoding != null ) ? outputEncoding : ReaderFactory.UTF_8; } static String getPmdVersion() { try { return (String) PMD.class.getField( "VERSION" ).get( null ); } catch ( IllegalAccessException e ) { throw new RuntimeException( "PMD VERSION field not accessible", e ); } catch ( NoSuchFieldException e ) { throw new RuntimeException( "PMD VERSION field not found", e ); } } } |
data class | data class, long method | t | t | t | long method | 0 | 13040 | https://github.com/apache/maven-plugins/blob/a007e769ed5825774d5c31ec06c0013c8ee2b4d4/maven-pmd-plugin/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java/#L52-L553 | 1 | 4807 | 13040 | minor | |
| 313 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void transformKeyReferences(RefTransformer visitor) { configs.forEach(c -> c.transformKeyReferences(visitor)); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 3219 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/android/resources/ResTableTypeSpec.java/#L166-L168 | 2 | 313 | 3219 | critical | ||
| 554 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer223 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer223() {} public Customer223(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer223[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 5603 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer223.java/#L8-L27 | 1 | 554 | 5603 | major | ||
| 2418 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PullPoint create(String queueName) throws UnableToCreatePullPointFault { org.oasis_open.docs.wsn.b_2.CreatePullPoint request = new org.oasis_open.docs.wsn.b_2.CreatePullPoint(); request.getOtherAttributes().put(NotificationBroker.QNAME_PULLPOINT_QUEUE_NAME, queueName); CreatePullPointResponse response = createPullPoint.createPullPoint(request); return new PullPoint(response.getPullPoint()); } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 14426 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/services/wsn/wsn-api/src/main/java/org/apache/cxf/wsn/client/CreatePullPoint.java/#L58-L64 | 1 | 2418 | 14426 | minor | |
| 2614 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DefaultTypeDeclaration extends AbstractDeclaration implements TypeDeclaration { private final Element m_componentMetadata; private final String m_componentName; private final String m_componentVersion; private final String m_extension; private boolean visible = true; public DefaultTypeDeclaration(BundleContext bundleContext, Element componentMetadata) { super(bundleContext, TypeDeclaration.class); m_componentMetadata = componentMetadata; visible = initVisible(); m_componentName = initComponentName(); m_componentVersion = initComponentVersion(bundleContext); m_extension = initExtension(); } private String initExtension() { if (m_componentMetadata.getNameSpace() == null) { return m_componentMetadata.getName(); } return m_componentMetadata.getNameSpace() + ":" + m_componentMetadata.getName(); } private String initComponentVersion(BundleContext bundleContext) { String version = m_componentMetadata.getAttribute("version"); if (version != null) { if ("bundle".equalsIgnoreCase(version)) { return bundleContext.getBundle().getHeaders().get(Constants.BUNDLE_VERSION); } } return version; } private String initComponentName() { String name = m_componentMetadata.getAttribute("name"); if (name == null) { name = m_componentMetadata.getAttribute("classname"); } return name; } private boolean initVisible() { String publicAttribute = m_componentMetadata.getAttribute("public"); return (publicAttribute == null) || !publicAttribute.equalsIgnoreCase("false"); } public String getComponentName() { return m_componentName; } public String getComponentVersion() { return m_componentVersion; } public String getExtension() { return m_extension; } public Element getComponentMetadata() { return m_componentMetadata; } public boolean isPublic() { return visible; } } |
data class | data class, long method | t | t | t | long method | 0 | 15045 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/extender/internal/declaration/DefaultTypeDeclaration.java/#L30-L96 | 1 | 2614 | 15045 | minor | |
| 891 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected void createButtonGroup( Group grpTop ) { btnAdd = new Button( grpTop, SWT.NONE ); { btnAdd.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Add" ) ); //$NON-NLS-1$ btnAdd.addSelectionListener( this ); } newMarkerEditor = new MarkerEditorComposite( grpTop, createMarker( ), getContext( ), getDefaultMarker( ) ); if ( markerTypeSet != null ) { newMarkerEditor.setSupportedMarkerTypes( markerTypeSet ); } if ( outlineText != null ) { newMarkerEditor.setOutlineText( outlineText ); } btnRemove = new Button( grpTop, SWT.NONE ); { btnRemove.setText( Messages.getString( "LineSeriesMarkerSheet.Label.Remove" ) ); //$NON-NLS-1$ btnRemove.addSelectionListener( this ); } btnUp = new Button( grpTop, SWT.ARROW | SWT.UP ); { btnUp.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Up" ) ); //$NON-NLS-1$ btnUp.addSelectionListener( this ); } btnDown = new Button( grpTop, SWT.ARROW | SWT.DOWN ); { btnDown.setToolTipText( Messages.getString( "PaletteEditorComposite.Lbl.Down" ) ); //$NON-NLS-1$ btnDown.addSelectionListener( this ); } } |
long method | long method | t | t | t | 0 | 8095 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/wizard/format/popup/series/LineSeriesMarkerSheet.java/#L402-L440 | 1 | 891 | 8095 | minor | ||
| 2135 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 13243 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 2135 | 13243 | major | ||
| 938 | YES I found bad smells The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 8427 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 938 | 8427 | minor | |
| 2065 | YES I found bad smells. The bad smells are: 1. Long method 2. Duplicate code 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static void walker(List> finalResult, final List> input, List listSoFar, final int level) throws SemanticException { // Base case. if (level == (input.size() - 1)) { assert (input.get(level) != null) : "Unique skewed element list has null list in " + level + "th position."; for (String v : input.get(level)) { List oneCompleteIndex = new ArrayList(listSoFar); oneCompleteIndex.add(v); finalResult.add(oneCompleteIndex); } return; } // Recursive. for (String v : input.get(level)) { List clonedListSoFar = new ArrayList(listSoFar); clonedListSoFar.add(v); int nextLevel = level + 1; walker(finalResult, input, clonedListSoFar, nextLevel); } } |
long method | Long method2 Duplicate code3 Feature envy | t | f | t | 0 | 12987 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPruner.java/#L612-L633 | 2 | 2065 | 12987 | minor | ||
| 1588 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager)componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); if (spm == null) { spm = new XMLSecurityPropertyManager(); setProperty(XML_SECURITY_PROPERTY_MANAGER, spm); } XMLSecurityManager sm = (XMLSecurityManager)componentManager.getProperty(SECURITY_MANAGER); if (sm == null) setProperty(SECURITY_MANAGER,new XMLSecurityManager(true)); faccessExternalSchema = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings = true; // If the component manager is the loader config don't bother querying it since it doesn't // recognize the PARSER_SETTINGS feature. Prevents an XMLConfigurationException from being // thrown. if (componentManager != fLoaderConfig) { parser_settings = componentManager.getFeature(PARSER_SETTINGS, true); } if (!parser_settings || !fSettingsChanged){ // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); if (fDeclPool != null) { fDeclPool.reset(); } return; } //pass the component manager to the factory.. fNodeFactory.reset(componentManager); // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // Determine schema dv factory to use SchemaDVFactory dvFactory = null; dvFactory = fSchemaHandler.getDVFactory(); if (dvFactory == null) { dvFactory = SchemaDVFactory.getInstance(); fSchemaHandler.setDVFactory(dvFactory); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE, null); fJAXPProcessed = false; // clear grammars, and put the one for schema namespace there fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL, null); initGrammarBucket(); boolean psvi = componentManager.getFeature(AUGMENT_PSVI, false); // Only use the decl pool when there is no chance that the schema // components will be exposed or cached. // TODO: when someone calls loadGrammar(XMLInputSource), the schema is // always exposed even without the use of a grammar pool. // Disabling the "decl pool" feature for now until we understand when // it can be safely used. if (!psvi && fGrammarPool == null && false) { if (fDeclPool != null) { fDeclPool.reset(); } else { fDeclPool = new XSDeclarationPool(); } fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); if (dvFactory instanceof SchemaDVFactoryImpl) { fDeclPool.setDVFactory((SchemaDVFactoryImpl)dvFactory); ((SchemaDVFactoryImpl)dvFactory).setDeclPool(fDeclPool); } } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); if (dvFactory instanceof SchemaDVFactoryImpl) { ((SchemaDVFactoryImpl)dvFactory).setDeclPool(null); } } // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR, false); if (!fatalError) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } } catch (XMLConfigurationException e) { } // set full validation to false fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING, false); // get generate-synthetic-annotations feature fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false)); fSchemaHandler.reset(componentManager); } |
long method | long method | t | t | t | 0 | 11376 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java/#L1000-L1116 | 1 | 1588 | 11376 | major | ||
| 579 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private Map tika_parse(InputStream sourceStream, String prefix, Integer maxAttribs, Integer maxAttribLen) throws IOException, TikaException, SAXException { final Metadata metadata = new Metadata(); final TikaInputStream tikaInputStream = TikaInputStream.get(sourceStream); try { autoDetectParser.parse(tikaInputStream, new DefaultHandler(), metadata); } finally { tikaInputStream.close(); } final Map results = new HashMap<>(); final Pattern metadataKeyFilter = metadataKeyFilterRef.get(); final StringBuilder dataBuilder = new StringBuilder(); for (final String key : metadata.names()) { if (metadataKeyFilter != null && !metadataKeyFilter.matcher(key).matches()) { continue; } dataBuilder.setLength(0); if (metadata.isMultiValued(key)) { for (String val : metadata.getValues(key)) { if (dataBuilder.length() > 1) { dataBuilder.append(", "); } if (dataBuilder.length() + val.length() < maxAttribLen) { dataBuilder.append(val); } else { dataBuilder.append("..."); break; } } } else { dataBuilder.append(metadata.get(key)); } if (prefix == null) { results.put(key, dataBuilder.toString().trim()); } else { results.put(prefix + key, dataBuilder.toString().trim()); } // cutoff at max if provided if (maxAttribs != null && results.size() >= maxAttribs) { break; } } return results; } |
long method | Long method, 2Magic numbers, 3 Feature envy | t | f | t | 2.Magic numbers, 3. Feature envy | 0 | 5784 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-media-bundle/nifi-media-processors/src/main/java/org/apache/nifi/processors/media/ExtractMediaMetadata.java/#L210-L255 | 2 | 579 | 5784 | major | |
| 2519 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 14706 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 2 | 2519 | 14706 | major | ||
| 1431 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ICompletionProposal[] getRelevantProposals( ITextViewer viewer, int offset ) throws BadLocationException { if ( lastProposals != null ) { ArrayList relevantProposals = new ArrayList( 10 ); String word = ( findWord( viewer, offset - 1 ) ).toLowerCase( ); //Search for this word in the list for ( int n = 0; n < lastProposals.length; n++ ) { if ( stripQuotes( lastProposals[n].getDisplayString( ) .toLowerCase( ) ).startsWith( word ) ) { CompletionProposal proposal = new CompletionProposal( lastProposals[n].getDisplayString( ), offset - word.length( ), word.length( ), lastProposals[n].getDisplayString( ).length( ) ); relevantProposals.add( proposal ); } } if ( relevantProposals.size( ) > 0 ) { return (ICompletionProposal[]) relevantProposals.toArray( new ICompletionProposal[]{} ); } } return null; } |
long method | Long method2 Feature envy | t | f | t | 0 | 10955 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/data/org.eclipse.birt.report.data.oda.jdbc.ui/src/org/eclipse/birt/report/data/oda/jdbc/ui/editors/JdbcSQLContentAssistProcessor.java/#L278-L308 | 2 | 1431 | 10955 | minor | ||
| 5777 | {"response": "YES I found bad smells", "bad smells are:": "1. Long method"} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
long method | 1. long method | t | t | t | 0 | 15213 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5777 | 15213 | minor | ||
| 5778 | { "message": "YES, I found bad smells", "bad smells are": [ "Long method", "Feature envy" ] } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map parameters) throws Exception { final int concurrentConsumers = getAndRemoveParameter(parameters, "concurrentConsumers", Integer.class, defaultConcurrentConsumers); final boolean limitConcurrentConsumers = getAndRemoveParameter(parameters, "limitConcurrentConsumers", Boolean.class, true); if (limitConcurrentConsumers && concurrentConsumers > MAX_CONCURRENT_CONSUMERS) { throw new IllegalArgumentException( "The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + MAX_CONCURRENT_CONSUMERS + " was " + concurrentConsumers); } if (concurrentConsumers < 0) { throw new IllegalArgumentException("concurrentConsumers found to be " + concurrentConsumers + ", must be greater than 0"); } int size = 0; if (parameters.containsKey("size")) { size = getAndRemoveParameter(parameters, "size", int.class); if (size <= 0) { throw new IllegalArgumentException("size found to be " + size + ", must be greater than 0"); } } // Check if the pollTimeout argument is set (may be the case if Disruptor component is used as drop-in // replacement for the SEDA component. if (parameters.containsKey("pollTimeout")) { throw new IllegalArgumentException("The 'pollTimeout' argument is not supported by the Disruptor component"); } final DisruptorWaitStrategy waitStrategy = getAndRemoveParameter(parameters, "waitStrategy", DisruptorWaitStrategy.class, defaultWaitStrategy); final DisruptorProducerType producerType = getAndRemoveParameter(parameters, "producerType", DisruptorProducerType.class, defaultProducerType); final boolean multipleConsumers = getAndRemoveParameter(parameters, "multipleConsumers", boolean.class, defaultMultipleConsumers); final boolean blockWhenFull = getAndRemoveParameter(parameters, "blockWhenFull", boolean.class, defaultBlockWhenFull); final DisruptorReference disruptorReference = getOrCreateDisruptor(uri, remaining, size, producerType, waitStrategy); final DisruptorEndpoint disruptorEndpoint = new DisruptorEndpoint(uri, this, disruptorReference, concurrentConsumers, multipleConsumers, blockWhenFull); disruptorEndpoint.setWaitStrategy(waitStrategy); disruptorEndpoint.setProducerType(producerType); disruptorEndpoint.configureProperties(parameters); return disruptorEndpoint; } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 15214 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorComponent.java/#L64-L108 | 2 | 5778 | 15214 | minor |
| 2497 | { "input": { "code_smells": [ "Blob", "Data Class", "Feature Envy", "Long Method" ], "java_code": "public class Example { public void doSomething() { // code here } }" }, "output": { "message": "YES I found bad smells", "detected_bad_smells": [ { "1": "Long Method" } ] } } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: |
long method | message: yes i found bad smells, detected_bad_smells: 1: long method | t | t | t | message: yes i found bad smells | 0 | 14646 | https://github.com/apache/kylin/blob/6ee0212af9d5b50096850c9cb76031b7cdd67402/core-common/src/main/java/org/apache/kylin/common/persistence/JDBCResourceStore.java/#L566-L591 | 1 | 2497 | 14646 | minor | |
| 996 | Yes, I found bad smells. The bad smells are: 1. Long method, 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Check public void checkNoForwardReferences(XExpression fieldInitializer) { JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer); if (container instanceof JvmField) { JvmField field = (JvmField) container; boolean staticField = field.isStatic(); JvmDeclaredType declaredType = field.getDeclaringType(); if (declaredType == null) { return; } Collection illegalFields = Sets.newHashSet(); for(int i = declaredType.getMembers().size() - 1; i>=0; i--) { JvmMember member = declaredType.getMembers().get(i); if (member instanceof JvmField) { if (((JvmField) member).isStatic() == staticField) { illegalFields.add((JvmField) member); } } if (member == field) break; } TreeIterator iterator = EcoreUtil2.eAll(fieldInitializer); while(iterator.hasNext()) { EObject object = iterator.next(); if (object instanceof XFeatureCall) { JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature(); if (illegalFields.contains(((XFeatureCall) object).getFeature())) { error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE); } } else if (isLocalClassSemantics(object)) { iterator.prune(); } } } } |
long method | Long method, 2 Feature envy, 3 Magic numbers, 4 Duplicate code, 5 Inconsistent naming conventions | t | f | t | 2. Feature envy, 3. Magic numbers, 4. Duplicate code, 5. Inconsistent naming conventions. | 0 | 9119 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/validation/XbaseValidator.java/#L1028-L1063 | 2 | 996 | 9119 | minor | |
| 4 | {"response":"YES I found bad smells","bad smells are":["Long Method","Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class MailChimpServiceImpl implements MailChimpService { private static Logger logger = LoggerFactory.getLogger(MailChimpServiceImpl.class); private static final String ACCEPT = "Accept"; private static final String AUTHORIZATION = "Authorization"; private static final String LISTS = "lists"; private static final String ID = "id"; private static final String NAME = "name"; private static final String MERGE_FIELDS = "merge_fields"; private static final String EMAIL_TYPE = "email_type"; private static final String EMAIL_ADDRESS = "email_address"; private static final String EMAIL = "email"; private static final String ERRORS = "errors"; private static final String LIST_IDENTIFIER = "listIdentifier"; private static final String STATUS = "status"; private static final String SUBSCRIBED = "subscribed"; private static final String UNSUBSCRIBED = "unsubscribed"; private static final String TAG = "tag"; private static final String TYPE = "type"; private static final String UNOMI_ID = "unomiId"; private static final String MC_SUB_TAG_NAME = "mcSubTagName"; private static final String ADDR_1 = "addr1"; private static final String ADDR_2 = "addr2"; private static final String CITY = "city"; private static final String COUNTRY = "country"; private static final String STATE = "state"; private static final String ZIP = "zip"; private static final String ADDRESS = "address"; private static final String DATE_FORMAT = "date_format"; private static final String OPTIONS = "options"; private static final String DATE = "date"; private static final String MC_MM_DD_YYYY = "MM/DD/YYYY"; private static final String MM_DD_YYYY = "MM/dd/yyyy"; private static final String DD_MM_YYYY = "dd/MM/yyyy"; private static final String BIRTHDAY = "birthday"; private static final String MC_MM_DD = "MM/DD"; private static final String MM_DD = "MM/dd"; private static final String DD_MM = "dd/MM"; private static final String SEPARATOR_CHARS_PROPERTIES = ","; private static final String SEPARATOR_CHARS_PROPERTY = "<=>"; private String apiKey; private String urlSubDomain; private Map>> listMergeFieldMapping; private Boolean isMergeFieldsActivate; private CloseableHttpClient httpClient; @Override public List> getAllLists() { List> mcLists = new ArrayList<>(); if (isMailChimpConnectorConfigured()) { JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists", getHeaders(), false); if (response != null) { if (response.has(LISTS) && response.get(LISTS).size() > 0) { for (JsonNode list : response.get(LISTS)) { if (list.has(ID) && list.has(NAME)) { HashMap mcListInfo = new HashMap<>(); mcListInfo.put(ID, list.get(ID).asText()); mcListInfo.put(NAME, list.get(NAME).asText()); mcLists.add(mcListInfo); } else { logger.warn("Missing mandatory information for list, {}", list.asText()); } } } else { logger.debug("No list to return, response was {}", response.asText()); } } } return mcLists; } @Override public MailChimpResult addToMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { logger.error("The visitor does not have an email address"); return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); JSONObject mergeFields = new JSONObject(); if (currentMember != null && currentMember.has(STATUS)) { JSONObject body = new JSONObject(); if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { logger.debug("The visitor is already in the MailChimp list, his status is unsubscribed"); body.put(STATUS, SUBSCRIBED); } if (isMergeFieldsActivate && addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields) == MailChimpResult.SUCCESS) { body.put(MERGE_FIELDS, mergeFields); } return updateSubscription(listIdentifier, body.toString(), currentMember, true); } JSONObject userData = new JSONObject(); userData.put(EMAIL_TYPE, "html"); userData.put(EMAIL_ADDRESS, profile.getProperty(EMAIL).toString()); userData.put(STATUS, SUBSCRIBED); if (isMergeFieldsActivate) { addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); } userData.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePostRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members", getHeaders(), userData.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when adding user to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } @Override public MailChimpResult removeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.NO_CHANGE; } JsonNode response = HttpUtils.executeDeleteRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Couldn't remove the visitor from the MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.REMOVED; } @Override public MailChimpResult unsubscribeFromMCList(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("Couldn't get the list identifier from Unomi"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { return MailChimpResult.REMOVED; } if (currentMember.get(STATUS).asText().equals(UNSUBSCRIBED)) { return MailChimpResult.NO_CHANGE; } JSONObject body = new JSONObject(); body.put(STATUS, UNSUBSCRIBED); return updateSubscription(listIdentifier, body.toString(), currentMember, false); } @Override public MailChimpResult updateMCProfileProperties(Profile profile, Action action) { if (!isMailChimpConnectorConfigured() || profile.getProperty(EMAIL) == null) { return MailChimpResult.ERROR; } String listIdentifier = (String) action.getParameterValues().get(LIST_IDENTIFIER); if (StringUtils.isBlank(listIdentifier)) { logger.warn("MailChimp list identifier not found"); return MailChimpResult.ERROR; } JsonNode currentMember = isMemberOfMailChimpList(profile, listIdentifier); if (currentMember == null) { logger.warn("The visitor was not part of the list"); return MailChimpResult.NO_CHANGE; } JSONObject mergeFields = new JSONObject(); MailChimpResult result = addProfilePropertiesToMergeFieldsObject(profile, listIdentifier, mergeFields); if (result != MailChimpResult.SUCCESS) { return result; } JSONObject body = new JSONObject(); body.put(MERGE_FIELDS, mergeFields); JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + currentMember.get(ID).asText(), getHeaders(), body.toString()); if (response == null || (response.has(ERRORS) && response.get(ERRORS).size() > 0)) { logger.error("Error when updating visitor properties to MailChimp list, list identifier was {} and response was {}", listIdentifier, response); return MailChimpResult.ERROR; } return MailChimpResult.UPDATED; } private MailChimpResult addProfilePropertiesToMergeFieldsObject(Profile profile, String listIdentifier, JSONObject mergeFields) { if (listMergeFieldMapping.isEmpty()) { logger.error("List of merge fields is not correctly configured"); return MailChimpResult.ERROR; } JsonNode mergeFieldsDefinitions = getMCListProperties(listIdentifier); if (mergeFieldsDefinitions == null) { logger.error("Could not get MailChimp list's merge fields"); return MailChimpResult.ERROR; } for (JsonNode mergeFieldDefinition : mergeFieldsDefinitions.get(MERGE_FIELDS)) { if (mergeFieldDefinition.has(TAG) && mergeFieldDefinition.has(TYPE)) { String mcTagName = mergeFieldDefinition.get(TAG).asText(); if (listMergeFieldMapping.containsKey(mcTagName)) { List> fields = listMergeFieldMapping.get(mcTagName); for (Map fieldInfo : fields) { String unomiId = fieldInfo.get(UNOMI_ID); if (profile.getProperty(unomiId) != null) { switch (mergeFieldDefinition.get(TYPE).asText()) { case ADDRESS: if (mergeFields.has(mcTagName)) { mergeFields.getJSONObject(mcTagName).put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); } else { JSONObject address = new JSONObject(); address.put(ADDR_1, ""); address.put(ADDR_2, ""); address.put(CITY, ""); address.put(COUNTRY, ""); address.put(STATE, ""); address.put(ZIP, ""); address.put(fieldInfo.get(MC_SUB_TAG_NAME), profile.getProperty(unomiId)); mergeFields.put(mcTagName, address); } break; case DATE: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; case BIRTHDAY: if (mergeFieldDefinition.has(OPTIONS) && mergeFieldDefinition.get(OPTIONS).has(DATE_FORMAT)) { mergeFields.put(mcTagName, formatDate(mergeFieldDefinition.get(OPTIONS).get(DATE_FORMAT).asText(), profile.getProperty(unomiId))); } break; default: mergeFields.put(mcTagName, profile.getProperty(unomiId)); break; } } } if (mergeFieldDefinition.get(TYPE).asText().equals(ADDRESS) && mergeFields.has(mcTagName) && (StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ADDR_1).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(ZIP).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(CITY).toString()) || StringUtils.isBlank(mergeFields.getJSONObject(mcTagName).get(COUNTRY).toString()))) { mergeFields.remove(mcTagName); logger.debug("Can't map the address property {}, one of the mandatory field is missing (addr1, zip, city, country)", mcTagName); } } else { logger.debug("Found property {} in MC list, if you need this property please update mapping or add the property to your MC list", mcTagName); } } } return MailChimpResult.SUCCESS; } private String formatDate(String mcDateFormat, Object date) { DateTime dateTime = new DateTime(date); if (StringUtils.contains(mcDateFormat, "/YYYY")) { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD_YYYY) ? MM_DD_YYYY : DD_MM_YYYY)).print(dateTime); } else { return DateTimeFormat.forPattern((mcDateFormat.equals(MC_MM_DD) ? MM_DD : DD_MM)).print(dateTime); } } private JsonNode getMCListProperties(String listIdentifier) { JsonNode currentMergeFields = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/merge-fields", getHeaders(), false); if (currentMergeFields == null || !currentMergeFields.has(MERGE_FIELDS)) { logger.error("Can't find merge_fields from the response, the response was {}", currentMergeFields); return null; } return currentMergeFields; } private void initHttpClient() { if (httpClient == null) { httpClient = HttpUtils.initHttpClient(); } } private boolean isMailChimpConnectorConfigured() { if (StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(urlSubDomain)) { initHttpClient(); return true; } logger.error("MailChimp extension isn't correctly configured, please check cfg file."); return false; } private JsonNode isMemberOfMailChimpList(Profile profile, String listIdentifier) { String email = profile.getProperty(EMAIL).toString().toLowerCase(); String md5Hex = DigestUtils.md5Hex(email); JsonNode response = HttpUtils.executeGetRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + md5Hex, getHeaders(), true); if (response != null) { if (response.has(EMAIL_ADDRESS)) { if (response.get(EMAIL_ADDRESS).asText().toLowerCase().equals(email)) { return response; } } } return null; } private MailChimpResult updateSubscription(String listIdentifier, String jsonData, JsonNode member, boolean toSubscribe) { JsonNode response = HttpUtils.executePatchRequest(httpClient, getBaseUrl() + "/lists/" + listIdentifier + "/members/" + member.get(ID).asText(), getHeaders(), jsonData); if (response != null) { if (response.has(STATUS)) { String responseStatus = response.get(STATUS).asText(); if ((toSubscribe && responseStatus.equals(SUBSCRIBED)) || (!toSubscribe && responseStatus.equals(UNSUBSCRIBED))) { return MailChimpResult.UPDATED; } else { return MailChimpResult.NO_CHANGE; } } } logger.error("Couldn't update the subscription of the visitor"); return MailChimpResult.ERROR; } private String getBaseUrl() { return "https://" + urlSubDomain + ".api.mailchimp.com/3.0"; } private HashMap getHeaders() { HashMap headers = new HashMap<>(); headers.put(ACCEPT, "application/json"); headers.put(AUTHORIZATION, "apikey " + apiKey); return headers; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setUrlSubDomain(String urlSubDomain) { this.urlSubDomain = urlSubDomain; } public void setListMergeFieldMapping(String listMergeFields) { this.listMergeFieldMapping = new HashMap<>(); if (StringUtils.isNotBlank(listMergeFields)) { String mergeFields[] = StringUtils.split(listMergeFields, SEPARATOR_CHARS_PROPERTIES); if (mergeFields.length > 0) { for (String mergeField : mergeFields) { if (StringUtils.isNotBlank(mergeField)) { String mergeFieldInfo[] = StringUtils.split(mergeField, SEPARATOR_CHARS_PROPERTY); if (mergeFieldInfo.length > 0) { Map fieldInfo = new HashMap<>(); fieldInfo.put(UNOMI_ID, mergeFieldInfo[0]); if (mergeFieldInfo.length == 3) { fieldInfo.put(MC_SUB_TAG_NAME, mergeFieldInfo[2]); } String mcTagName = mergeFieldInfo[1]; if (listMergeFieldMapping.containsKey(mcTagName)) { listMergeFieldMapping.get(mcTagName).add(fieldInfo); } else { List> fields = new ArrayList<>(); fields.add(fieldInfo); listMergeFieldMapping.put(mcTagName, fields); } } } } } } } public void setIsMergeFieldsActivate(Boolean isMergeFieldsActivate) { this.isMergeFieldsActivate = isMergeFieldsActivate; } } |
data class | long method, data class | t | t | f | long method | data class | 0 | 555 | https://github.com/apache/unomi/blob/1745c5221401a05e66ebf80fbe9cce2790442b3a/extensions/unomi-mailchimp/services/src/main/java/org/apache/unomi/mailchimp/services/internal/MailChimpServiceImpl.java/#L40-L434 | 1 | 4 | 555 | minor |
| 1692 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Duplicate code 4. Complex conditional statements 5. Inappropriate exception handling 6. Poor naming conventions 7. Lack of modularity and encapsulation | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException { AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName()); if (parentRule != null) { if (parentRule != rule && parentRule instanceof ParserRule) { ParserRule casted = (ParserRule) parentRule; if (casted.isFragment() != rule.isFragment()) { if (rule.isFragment()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A fragment rule cannot override a production rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only fragment rule can override other fragment rules.", rule); } } if (casted.isWildcard() != rule.isWildcard()) { if (rule.isWildcard()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "A wildcard fragment rule cannot override a typed fragment rule.", rule); } else { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Only wildcard fragment rules can override other wildcard fragments.", rule); } } if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) { if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) { throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride, "Overriding fragment rules cannot redeclare their type.", rule.getType()); } } checkParameterLists(rule, casted); } if (parentRule.getType() != null && parentRule != rule) { if (parentRule.getType().getClassifier() instanceof EDataType) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot inherit from datatype rule and return another type.", rule.getType()); EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType()); if (parentTypeInfo == null) throw new TransformationException(TransformationErrorCode.InvalidSupertype, "Cannot determine return type of overridden rule.", rule.getType()); addSuperType(rule, rule.getType(), parentTypeInfo); return true; } } return false; } |
long method | Long method 2 Feature envy 3 Duplicate code 4 Complex conditional statements 5 Inappropriate exception handling 6 Poor naming conventions 7 Lack of modularity and encapsulation | t | f | t | 0 | 11712 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext/src/org/eclipse/xtext/xtext/ecoreInference/Xtext2EcoreTransformer.java/#L720-L764 | 2 | 1692 | 11712 | major | ||
| 548 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
feature envy | long method, feature envy | t | t | f | long method | feature envy | 0 | 5554 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 1 | 548 | 5554 | minor |
| 1887 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: TreeNodeChildren(final TreeNode parent, final Object metadata, final PropertyAccessor accessor) { this.parent = parent; this.metadata = metadata; this.accessor = accessor; this.children = new TreeNode[accessor.count()]; /* * Search for something that looks like the main property, to be associated with the parent node * instead than provided as a child. The intent is to have more compact and easy to read trees. * That property shall be a singleton for a simple value (not another metadata object). */ if (parent.table.valuePolicy == ValueExistencePolicy.COMPACT) { TitleProperty an = accessor.implementation.getAnnotation(TitleProperty.class); if (an == null) { Class implementation = parent.table.standard.getImplementation(accessor.type); if (implementation != null) { an = implementation.getAnnotation(TitleProperty.class); } } if (an != null) { final int index = accessor.indexOf(an.name(), false); final Class type = accessor.type(index, TypeValuePolicy.ELEMENT_TYPE); if (type != null && !parent.isMetadata(type) && type == accessor.type(index, TypeValuePolicy.PROPERTY_TYPE)) { titleProperty = index; return; } } } titleProperty = -1; } |
long method | blob, long method | t | t | t | blob | 0 | 12299 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/metadata/TreeNodeChildren.java/#L137-L165 | 1 | 1887 | 12299 | minor | |
| 1809 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Nullable public static PropertyEditor findEditorByConvention(@Nullable Class targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isInfoEnabled()) { logger.info("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 12052 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java/#L504-L546 | 2 | 1809 | 12052 | minor | |
| 795 | YES I found bad smells the bad smells are: 1. Long method 2. Switch statement 3. Duplicate code in each case of the switch statement 4. Conditional complexity 5. Magic numbers (e.g. "yyyy" for year, "MM" for month, etc.) 6. Feature envy (each case using a different format string instead of using a single method to format the date) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private SimpleDateFormat createFormat(DateResolution dateResolution) { switch (dateResolution) { case Year: return new SimpleDateFormat("yyyy"); case Month: return new SimpleDateFormat("yyyyMM"); case Day: return new SimpleDateFormat("yyyyMMdd"); case Hour: return new SimpleDateFormat("yyyyMMddhh"); case Minute: return new SimpleDateFormat("yyyyMMddhhmm"); case Second: return new SimpleDateFormat("yyyyMMddhhmmss"); default: return new SimpleDateFormat("yyyyMMddhhmmssSSS"); } } |
long method | Long method2 Switch statement3 Duplicate code in each case of the switch statement4 Conditional complexity5 Magic numbers (eg "yyyy" for year, "MM" for month, etc)6 Feature envy (each case using a different format string instead of using a single method to format the date) | t | f | t | "MM" for month, etc.)6. Feature envy (each case using a different format string instead of using a single method to format the date) | 0 | 7555 | https://github.com/apache/james-project/blob/fa24a096a5853459c3769a34ccc68feb91626bfa/mailbox/store/src/main/java/org/apache/james/mailbox/store/search/MessageSearches.java/#L624-L641 | 2 | 795 | 7555 | minor | |
| 335 | {"message": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: void getHashes(List searchHashes, int bitShift) { // We don't need to include 0 because that's always assumed in look ups. If we do return 0, that // means this agent isn't sure what it needs, but the inverse is acceptable because that just // means the airing doesn't know what it matches and it will be tested on all of the agents. searchHashes.clear(); if (title != null) { searchHashes.add((title.ignoreCaseHash >>> bitShift)); } if (person != null) { addHash(person.ignoreCaseHash, searchHashes, bitShift); } if (category != null) { addHash(category.ignoreCaseHash, searchHashes, bitShift); } if (subCategory != null) { addHash(subCategory.ignoreCaseHash, searchHashes, bitShift); } if (chanName.length() > 0) { addHash(chanName.hashCode(), searchHashes, bitShift); } if (chanNames != null && chanNames.length > 0) { for (String chanName : chanNames) { addHash(chanName.hashCode(), searchHashes, bitShift); } } if (network != null) { addHash(network.ignoreCaseHash, searchHashes, bitShift); } if (rated != null) { addHash(rated.ignoreCaseHash, searchHashes, bitShift); } if (year != null) { addHash(year.ignoreCaseHash, searchHashes, bitShift); } if (pr != null) { addHash(pr.ignoreCaseHash, searchHashes, bitShift); } // This will ensure that we do a full search since 0 means at least one of our items doesn't // have a "valid" hash. if (searchHashes.contains(0)) searchHashes.clear(); } |
long method | long method | t | t | t | 0 | 3439 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/Agent.java/#L1825-L1889 | 1 | 335 | 3439 | major | ||
| 1081 | { "output": "YES I found bad smells, the bad smells are: 1. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ItemContent { private String defaultName = ""; //$NON-NLS-1$ private String displayName = ""; //$NON-NLS-1$ private String customName = ""; //$NON-NLS-1$ private String description = ""; //$NON-NLS-1$ public ItemContent( String string ) { super( ); this.setCustomName( string ); } /** * * @return Return the default name of ItemContent */ public String getDefaultName( ) { return defaultName; } /** * * @return Returns the display name of the ItemContent */ public String getDisplayName( ) { return displayName; } /** * Set default name for ItemContent * * @param string */ public void setDefaultName( String string ) { defaultName = string.trim( ); } /** * Sets the display name for the ItemContent * * @param string */ public void setDisplayName( String string ) { displayName = string.trim( ); } /** * * @return custom name of ItemContent */ public String getCustomName( ) { return customName; } /** * Set custom name for ItemContent * * @param string */ public void setCustomName( String string ) { customName = string.trim( ); } /** * * @return the description of ItemContent */ public String getDescription( ) { return description; } /** * Set the description for ItemContent * * @param string */ public void setDescription( String string ) { description = string.trim( ); } } |
data class | 1. data class | t | t | t | 0 | 9680 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/preferences/ItemContent.java/#L22-L112 | 1 | 1081 | 9680 | major | ||
| 2914 | YES I found bad smells the bad smells are: 1. Data Class | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static class FieldMetaData { public final FieldInfo fieldInfo; public final long numTerms; public final long sumTotalTermFreq; public final long sumDocFreq; public final int docCount; public final int longsSize; public final FST dict; public FieldMetaData(FieldInfo fieldInfo, long numTerms, long sumTotalTermFreq, long sumDocFreq, int docCount, int longsSize, FST fst) { this.fieldInfo = fieldInfo; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.longsSize = longsSize; this.dict = fst; } } |
data class | Data Class | t | f | t | 0 | 2250 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java/#L229-L247 | 2 | 2914 | 2250 | major | ||
| 1957 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Primitive obsession | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void validateArrayStep(String arrStep) throws QueryException { boolean wildAllowed = true; // * is allowed initially boolean digitAllowed = true; // Digit is allowed as next char boolean commaAllowed = false; // Comma is allowed as next char boolean afterDigit = false; // Last non-space was a digit boolean toAllowed = false; // Any space after digit allows "to" boolean afterTo = false; // After "to" expecting range end boolean toInProgress = false; // Prior char was 't' in "to" boolean spaceRequired = false; // A whitespace is required (after "to") boolean digitRequired = false; // Digit required after comma or "to" for (int i = 1; i < arrStep.length() - 1; ++i) { char currentChar = arrStep.charAt(i); if (currentChar == '*') { if (!wildAllowed) throwArrayException(arrStep); wildAllowed = false; // We've seen the only allowed wildcard digitAllowed = false; // Only whitespace is allowed afterward } else if (currentChar == ',') { if (!commaAllowed) throwArrayException(arrStep); commaAllowed = false; toAllowed = false; afterDigit = false; afterTo = false; digitRequired = true; // Next non-space must be a digit } else if ("0123456789".indexOf(currentChar) >= 0) { if (!digitAllowed) throwArrayException(arrStep); wildAllowed = false; // Wildcard no longer allowed commaAllowed = true; afterDigit = true; digitRequired = false; } else if (" \t\n\r".indexOf(currentChar) >= 0) { // Whitespace not allowed when parsing "to" if (toInProgress) throwArrayException(arrStep); if (afterDigit) { // Last non-space was a digit - next non-space is "to" or comma digitAllowed = false; toAllowed = !afterTo; commaAllowed = true; } else if (spaceRequired) { // This is the whitespace required after "to" digitAllowed = true; spaceRequired = false; digitRequired = true; // At least one digit must follow } } else if (currentChar == 't') { if (!toAllowed) throwArrayException(arrStep); toInProgress = true; // Next char must be the 'o' in "to" commaAllowed = false; afterDigit = false; } else if (currentChar == 'o') { if (!toInProgress) throwArrayException(arrStep); toInProgress = false; toAllowed = false; afterTo = true; spaceRequired = true; // "to" must be followed by whitespace } else { // Invalid character throwArrayException(arrStep); } } // Empty array or only whitespace found if (wildAllowed) throwArrayException(arrStep); // Incomplete "to" or comma sequence at end of subscript if (toInProgress || spaceRequired || digitRequired) throwArrayException(arrStep); } |
long method | Long method2 Feature envy3 Primitive obsession | t | f | t | 0 | 12568 | https://github.com/oracle/soda-for-java/blob/352634e26b5a0d9d529d5436f7a4c8e21ed1dbf0/src/oracle/json/parser/PathParser.java/#L138-L239 | 2 | 1957 | 12568 | critical | ||
| 361 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 3699 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 361 | 3699 | major | ||
| 2218 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class DQ_EvaluationMethodTypeCode extends CodeListAdapter { /** * Empty constructor for JAXB only. */ public DQ_EvaluationMethodTypeCode() { } /** * Creates a new adapter for the given value. */ private DQ_EvaluationMethodTypeCode(final CodeListUID value) { super(value); } /** * {@inheritDoc} * * @return the wrapper for the code list value. */ @Override protected DQ_EvaluationMethodTypeCode wrap(final CodeListUID value) { return new DQ_EvaluationMethodTypeCode(value); } /** * {@inheritDoc} * * @return the code list class. */ @Override protected Class getCodeListClass() { return EvaluationMethodType.class; } /** * Invoked by JAXB on marshalling. * * @return the value to be marshalled. */ @Override @XmlElement(name = "DQ_EvaluationMethodTypeCode", namespace = Namespaces.MDQ) public CodeListUID getElement() { return identifier; } /** * Invoked by JAXB on unmarshalling. * * @param value the unmarshalled value. */ public void setElement(final CodeListUID value) { identifier = value; } } |
data class | 1. data class | t | t | t | 0 | 13542 | https://github.com/apache/sis/blob/002121abc9b9826fbd51fac7150b3ee0c02cc88b/core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/code/DQ_EvaluationMethodTypeCode.java/#L36-L91 | 1 | 2218 | 13542 | minor | ||
| 428 | { "message": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class AvroWrapper { private T datum; /** Wrap null. Construct {@link AvroWrapper} wrapping no datum. */ public AvroWrapper() { this(null); } /** Wrap a datum. */ public AvroWrapper(T datum) { this.datum = datum; } /** Return the wrapped datum. */ public T datum() { return datum; } /** Set the wrapped datum. */ public void datum(T datum) { this.datum = datum; } @Override public int hashCode() { return (datum == null) ? 0 : datum.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AvroWrapper that = (AvroWrapper)obj; if (this.datum == null) { return that.datum == null; } else return datum.equals(that.datum); } /** Get the wrapped datum as JSON. */ @Override public String toString() { return datum.toString(); } } |
data class | data class | t | t | t | 0 | 4270 | https://github.com/apache/avro/blob/1119b6eb5b92730b27e9798793bc67f192591c15/lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroWrapper.java/#L22-L61 | 1 | 428 | 4270 | major | ||
| 1490 | {"answer": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public synchronized void start(BundleContext context) throws Exception { PermissionAdminImpl pai = null; SecureAction action = new SecureAction(); Permissions permissions = new Permissions(context, action); File tmp = context.getDataFile("security" + File.separator + "tmp"); if ((tmp == null) || (!tmp.isDirectory() && !tmp.mkdirs())) { throw new IOException("Can't create tmp dir."); } // TODO: log something if we can not clean-up the tmp dir File[] old = tmp.listFiles(); if (old != null) { for (int i = 0; i < old.length; i++) { old[i].delete(); } } if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_PERMISSIONADMIN_PROP, SecurityConstants.ENABLE_PERMISSIONADMIN_VALUE))) { File cache = context.getDataFile("security" + File.separator + "pa.txt"); if ((cache == null) || (!cache.isFile() && !cache.createNewFile())) { throw new IOException("Can't create cache file"); } pai = new PermissionAdminImpl(permissions, new PropertiesCache( cache, tmp, action)); } ConditionalPermissionAdminImpl cpai = null; if ("TRUE".equalsIgnoreCase(getProperty(context, SecurityConstants.ENABLE_CONDPERMADMIN_PROP, SecurityConstants.ENABLE_CONDPERMADMIN_VALUE))) { File cpaCache = context.getDataFile("security" + File.separator + "cpa.txt"); if ((cpaCache == null) || (!cpaCache.isFile() && !cpaCache.createNewFile())) { throw new IOException("Can't create cache file"); } LocalPermissions localPermissions = new LocalPermissions( permissions); cpai = new ConditionalPermissionAdminImpl(permissions, new Conditions(action), localPermissions, new PropertiesCache( cpaCache, tmp, action), pai); } if ((pai != null) || (cpai != null)) { String crlList = getProperty(context, SecurityConstants.CRL_FILE_PROP, SecurityConstants.CRL_FILE_VALUE); String storeList = getProperty(context, SecurityConstants.KEYSTORE_FILE_PROP, SecurityConstants.KEYSTORE_FILE_VALUE); String passwdList = getProperty(context, SecurityConstants.KEYSTORE_PASS_PROP, SecurityConstants.KEYSTORE_PASS_VALUE); String typeList = getProperty(context, SecurityConstants.KEYSTORE_TYPE_PROP, SecurityConstants.KEYSTORE_TYPE_VALUE); String osgi_keystores = getProperty(context, Constants.FRAMEWORK_TRUST_REPOSITORIES, null); if (osgi_keystores != null) { StringTokenizer tok = new StringTokenizer(osgi_keystores, File.pathSeparator); if (storeList.length() == 0) { storeList += "file:" + tok.nextToken(); passwdList += " "; typeList += "JKS"; } while (tok.hasMoreTokens()) { storeList += "|file:" + tok.nextToken(); passwdList += "| "; typeList += "|JKS"; } } StringTokenizer storeTok = new StringTokenizer(storeList, "|"); StringTokenizer passwdTok = new StringTokenizer(passwdList, "|"); StringTokenizer typeTok = new StringTokenizer(typeList, "|"); if ((storeTok.countTokens() != typeTok.countTokens()) || (passwdTok.countTokens() != storeTok.countTokens())) { throw new BundleException( "Each CACerts keystore must have one type and one passwd entry and vice versa."); } SecurityProvider provider = new SecurityProviderImpl(crlList, typeList, passwdList, storeList, pai, cpai, action, ((Felix) context.getBundle(0)).getLogger()); ((Felix) context.getBundle(0)).setSecurityProvider(provider); } if (pai != null) { context.registerService(PermissionAdmin.class.getName(), pai, null); } if (cpai != null) { context.registerService(ConditionalPermissionAdmin.class.getName(), cpai, null); } } |
long method | long method | t | t | t | 0 | 11110 | https://github.com/apache/felix/blob/a132994b250751d4ba3b115ee070ba397d9840ca/framework.security/src/main/java/org/apache/felix/framework/SecurityActivator.java/#L99-L220 | 1 | 1490 | 11110 | critical | ||
| 663 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final Element getDocumentElement() { int dochandle=dtm.getDocument(); int elementhandle=DTM.NULL; for(int kidhandle=dtm.getFirstChild(dochandle); kidhandle!=DTM.NULL; kidhandle=dtm.getNextSibling(kidhandle)) { switch(dtm.getNodeType(kidhandle)) { case Node.ELEMENT_NODE: if(elementhandle!=DTM.NULL) { elementhandle=DTM.NULL; // More than one; ill-formed. kidhandle=dtm.getLastChild(dochandle); // End loop } else elementhandle=kidhandle; break; // These are harmless; document is still wellformed case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_TYPE_NODE: break; default: elementhandle=DTM.NULL; // ill-formed kidhandle=dtm.getLastChild(dochandle); // End loop break; } } if(elementhandle==DTM.NULL) throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR); else return (Element)(dtm.getNode(elementhandle)); } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 6456 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMNodeProxy.java/#L619-L656 | 2 | 663 | 6456 | major | ||
| 513 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code, 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected void buildContent( ) { // Defines provider. IDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); // Defines section. TextSection nameSection = new TextSection( nameProvider.getDisplayName( ), container, true ); nameSection.setProvider( nameProvider ); nameSection.setLayoutNum( 6 ); nameSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_NAME, nameSection ); //$NON-NLS-1$ ComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); variableTypeProvider.enableReset( true ); ComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ), container, true ); variableTypeSection.setProvider( variableTypeProvider ); variableTypeSection.setLayoutNum( 6 ); variableTypeSection.setWidth( 500 ); addSection( PageSectionId.VARIABLE_TYPE, variableTypeSection ); ExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP, ReportDesignConstants.VARIABLE_ELEMENT ); ExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ), container, true ); variableValueSection.setMulti(false); variableValueSection.setProvider( variableValueProvider ); variableValueSection.setWidth( 500 ); variableValueSection.setLayoutNum( 6 ); addSection( PageSectionId.VARIABLE_VALUE, variableValueSection ); } |
long method | Long method, 2 Duplicate code, 3 Feature envy | t | f | t | 2. Duplicate code, 3. Feature envy | 0 | 5219 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/UI/org.eclipse.birt.report.designer.ui.views/src/org/eclipse/birt/report/designer/internal/ui/views/attributes/page/VariablePage.java/#L32-L74 | 2 | 513 | 5219 | minor | |
| 169 | {"message": "YES I found bad smells", "bad smells are": ["Long method"]} |
I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) { if (dc.getNetworkType() != NetworkType.Advanced) { throw new CloudRuntimeException("Zone " + dc + " is not advanced."); } if (dc.isSecurityGroupEnabled()) { List networks = _networkDao.listByZoneSecurityGroup(dc.getId()); if (CollectionUtils.isEmpty(networks)) { throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc); } return networks.get(0); } else { TrafficType defaultTrafficType = TrafficType.Public; List defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType); // api should never allow this situation to happen if (defaultNetworks.size() != 1) { throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1"); } return defaultNetworks.get(0); } } |
long method | long method | t | t | t | 0 | 2032 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java/#L696-L720 | 2 | 169 | 2032 | minor | ||
| 1480 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Device { private String id; private String deviceType; private String name; private Authentication authentication; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Authentication getAuthentication() { return authentication; } public void setAuthentication(Authentication authentication) { this.authentication = authentication; } } |
data class | data class | t | t | t | 0 | 11078 | https://github.com/SAP/iot-starterkit/blob/f0d9ce06a1a98569a5a4eed76a2ec0aa87c1a1df/neo/apps/java/authentication/com.sap.iot.starterkit.cert/src/main/java/com/sap/iot/starterkit/cert/type/Device.java/#L3-L45 | 1 | 1480 | 11078 | major | ||
| 620 | {"response": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public List> getNamedContexts(final SerializationContextMap map) { final ArrayList> result = CollectionLiterals.>newArrayList(); final HashMap names = CollectionLiterals.newHashMap(); List> _values = map.values(); for (final SerializationContextMap.Entry e : _values) { Set _types = e.getTypes(); for (final EClass t : _types) { { final List ctx = e.getContexts(t); String _xifexpression = null; if ((t == null)) { _xifexpression = ""; } else { _xifexpression = t.getName(); } String _plus = (_xifexpression + "_"); String _significantGrammarElement = this.getSignificantGrammarElement(ctx); final String name = (_plus + _significantGrammarElement); final Integer dup = names.get(name); String _xifexpression_1 = null; if ((dup == null)) { String _xblockexpression = null; { names.put(name, Integer.valueOf(1)); _xblockexpression = name; } _xifexpression_1 = _xblockexpression; } else { String _xblockexpression_1 = null; { names.put(name, Integer.valueOf(((dup).intValue() + 1))); _xblockexpression_1 = ((name + "_") + dup); } _xifexpression_1 = _xblockexpression_1; } final String unique = _xifexpression_1; T _value = e.getValue(); NamedSerializationContexts _namedSerializationContexts = new NamedSerializationContexts(unique, t, ctx, _value); result.add(_namedSerializationContexts); } } } return result; } |
long method | long method, data class | t | t | t | data class | 0 | 6215 | https://github.com/eclipse/xtext-core/blob/e04964e4c2a3e0338c0079bd8333688835e77c31/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java/#L45-L88 | 1 | 620 | 6215 | minor | |
| 1494 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SysInfo implements Serializable { static final long serialVersionUID = -3096346807579L; public int numCores; public long maxMemory; public SysInfo(int nc, long mm) { numCores = nc; maxMemory = mm; } } |
data class | data class | t | t | t | 0 | 11123 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/sjavac/server/SysInfo.java/#L45-L56 | 1 | 1494 | 11123 | major | ||
| 2572 | YES I found bad smells, the bad smells are: 1.Magic numbers, 2.Data class, 3. Long method, 4.Feature envy: | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: class ColumnFamilyRegionInfo { private RegionInfo regionInfo; private Set familySet; public ColumnFamilyRegionInfo(RegionInfo regionInfo, Set familySet) { this.regionInfo = regionInfo; this.familySet = familySet; } public RegionInfo getRegionInfo() { return regionInfo; } public Set getFamilySet() { return familySet; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ColumnFamilyRegionInfo)) { return false; } ColumnFamilyRegionInfo c = (ColumnFamilyRegionInfo)obj; return c.getRegionInfo().equals(this.regionInfo) && ByteUtil.match(this.familySet, c.getFamilySet()); } @Override public int hashCode() { return this.getRegionInfo().hashCode(); } } |
data class | Magic numbers, 2Data class, 3 Long method, 4Feature envy: | t | f | t | .Magic numbers, 3. Long method, 4.Feature envy: | 0 | 14907 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/schema/stats/StatisticsCollectionRunTracker.java/#L129-L159 | 2 | 2572 | 14907 | minor | |
| 1343 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy | t | f | t | 0 | 10745 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1343 | 10745 | minor | ||
| 1875 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void parseArray(NameSegment nameSeg) { String name = nameSeg.getPath(); ArraySegment arraySeg = ((ArraySegment) nameSeg.getChild()); int index = arraySeg.getIndex(); RequestedColumnImpl member = getImpl(name); if (member == null) { member = new RequestedColumnImpl(this, name); projection.add(name, member); } else if (member.isSimple()) { // Saw both a and a[x]. Occurs in project list. // Project all elements. member.projectAllElements(); return; } else if (member.hasIndex(index)) { throw UserException .validationError() .message("Duplicate array index in project list: %s[%d]", member.fullName(), index) .build(logger); } member.addIndex(index); // Drills SQL parser does not support map arrays: a[0].c // But, the SchemaPath does support them, so no harm in // parsing them here. if (! arraySeg.isLastPath()) { parseInternal(nameSeg); } } |
long method | Long method2 Feature envy | t | f | t | 0 | 12262 | https://github.com/apache/drill/blob/5e2251a9fd659b81ebfcd6702ee4ee16b3f7b6b3/exec/java-exec/src/main/java/org/apache/drill/exec/physical/rowSet/project/RequestedTupleImpl.java/#L260-L291 | 2 | 1875 | 12262 | minor | ||
| 1633 | { "output": "YES I found bad smells\nthe bad smells are: 1. Data class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class RestConfiguration { public static final String CORS_ACCESS_CONTROL_ALLOW_ORIGIN = "*"; public static final String CORS_ACCESS_CONTROL_ALLOW_METHODS = "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"; public static final String CORS_ACCESS_CONTROL_MAX_AGE = "3600"; public static final String CORS_ACCESS_CONTROL_ALLOW_HEADERS = "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"; public enum RestBindingMode { auto, off, json, xml, json_xml } public enum RestHostNameResolver { allLocalIp, localIp, localHostName } private String component; private String apiComponent; private String producerComponent; private String producerApiDoc; private String scheme; private String host; private boolean useXForwardHeaders = true; private String apiHost; private int port; private String contextPath; private String apiContextPath; private String apiContextRouteId; private String apiContextIdPattern; private boolean apiContextListing; private boolean apiVendorExtension; private RestHostNameResolver hostNameResolver = RestHostNameResolver.allLocalIp; private RestBindingMode bindingMode = RestBindingMode.off; private boolean skipBindingOnErrorCode = true; private boolean clientRequestValidation; private boolean enableCORS; private String jsonDataFormat; private String xmlDataFormat; private Map componentProperties; private Map endpointProperties; private Map consumerProperties; private Map dataFormatProperties; private Map apiProperties; private Map corsHeaders; /** * Gets the name of the Camel component to use as the REST consumer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getComponent() { return component; } /** * Sets the name of the Camel component to use as the REST consumer * * @param componentName the name of the component (such as restlet, spark-rest, etc.) */ public void setComponent(String componentName) { this.component = componentName; } /** * Gets the name of the Camel component to use as the REST API (such as swagger) * * @return the component name, or null to let Camel use the default name swagger */ public String getApiComponent() { return apiComponent; } /** * Sets the name of the Camel component to use as the REST API (such as swagger) * * @param apiComponent the name of the component (such as swagger) */ public void setApiComponent(String apiComponent) { this.apiComponent = apiComponent; } /** * Gets the name of the Camel component to use as the REST producer * * @return the component name, or null to let Camel search the {@link Registry} to find suitable implementation */ public String getProducerComponent() { return producerComponent; } /** * Sets the name of the Camel component to use as the REST producer * * @param componentName the name of the component (such as restlet, jetty, etc.) */ public void setProducerComponent(String componentName) { this.producerComponent = componentName; } /** * Gets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. */ public String getProducerApiDoc() { return producerApiDoc; } /** * Sets the location of the api document (swagger api) the REST producer will use * to validate the REST uri and query parameters are valid accordingly to the api document. * This requires adding camel-swagger-java to the classpath, and any miss configuration * will let Camel fail on startup and report the error(s). * * The location of the api document is loaded from classpath by default, but you can use * file: or http: to refer to resources to load from file or http url. */ public void setProducerApiDoc(String producerApiDoc) { this.producerApiDoc = producerApiDoc; } /** * Gets the hostname to use by the REST consumer * * @return the hostname, or null to use default hostname */ public String getHost() { return host; } /** * Sets the hostname to use by the REST consumer * * @param host the hostname */ public void setHost(String host) { this.host = host; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. */ public boolean isUseXForwardHeaders() { return useXForwardHeaders; } /** * WWhether to use X-Forward headers to set host etc. for Swagger. * * This option is default true. * * @param useXForwardHeaders whether to use X-Forward headers */ public void setUseXForwardHeaders(boolean useXForwardHeaders) { this.useXForwardHeaders = useXForwardHeaders; } public String getApiHost() { return apiHost; } /** * To use an specific hostname for the API documentation (eg swagger) * * This can be used to override the generated host with this configured hostname */ public void setApiHost(String apiHost) { this.apiHost = apiHost; } /** * Gets the scheme to use by the REST consumer * * @return the scheme, or null to use default scheme */ public String getScheme() { return scheme; } /** * Sets the scheme to use by the REST consumer * * @param scheme the scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Gets the port to use by the REST consumer * * @return the port, or 0 or -1 to use default port */ public int getPort() { return port; } /** * Sets the port to use by the REST consumer * * @param port the port number */ public void setPort(int port) { this.port = port; } /** * Gets the configured context-path * * @return the context path, or null if none configured. */ public String getContextPath() { return contextPath; } /** * Sets a leading context-path the REST services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. Or for components such as camel-jetty or camel-netty4-http * that includes a HTTP server. * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getApiContextPath() { return apiContextPath; } /** * Sets a leading API context-path the REST API services will be using. * * This can be used when using components such as camel-servlet where the deployed web application * is deployed using a context-path. * * @param contextPath the API context path */ public void setApiContextPath(String contextPath) { this.apiContextPath = contextPath; } public String getApiContextRouteId() { return apiContextRouteId; } /** * Sets the route id to use for the route that services the REST API. * * The route will by default use an auto assigned route id. * * @param apiContextRouteId the route id */ public void setApiContextRouteId(String apiContextRouteId) { this.apiContextRouteId = apiContextRouteId; } public String getApiContextIdPattern() { return apiContextIdPattern; } /** * Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. * * The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. * For any other value, the pattern uses the rules from {@link org.apache.camel.support.EndpointHelper#matchPattern(String, String)} * * @param apiContextIdPattern the pattern */ public void setApiContextIdPattern(String apiContextIdPattern) { this.apiContextIdPattern = apiContextIdPattern; } public boolean isApiContextListing() { return apiContextListing; } /** * Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover * these contexts, if false then only the current CamelContext is in use. */ public void setApiContextListing(boolean apiContextListing) { this.apiContextListing = apiContextListing; } public boolean isApiVendorExtension() { return apiVendorExtension; } /** * Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information * as vendor extension (eg keys starting with x-) such as route ids, class names etc. * Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. */ public void setApiVendorExtension(boolean apiVendorExtension) { this.apiVendorExtension = apiVendorExtension; } /** * Gets the resolver to use for resolving hostname * * @return the resolver */ public RestHostNameResolver getHostNameResolver() { return hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(RestHostNameResolver hostNameResolver) { this.hostNameResolver = hostNameResolver; } /** * Sets the resolver to use for resolving hostname * * @param hostNameResolver the resolver */ public void setHostNameResolver(String hostNameResolver) { this.hostNameResolver = RestHostNameResolver.valueOf(hostNameResolver); } /** * Gets the binding mode used by the REST consumer * * @return the binding mode */ public RestBindingMode getBindingMode() { return bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(RestBindingMode bindingMode) { this.bindingMode = bindingMode; } /** * Sets the binding mode to be used by the REST consumer * * @param bindingMode the binding mode */ public void setBindingMode(String bindingMode) { this.bindingMode = RestBindingMode.valueOf(bindingMode); } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @return whether to skip binding on error code */ public boolean isSkipBindingOnErrorCode() { return skipBindingOnErrorCode; } /** * Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. * * This option is default true. * * @param skipBindingOnErrorCode whether to skip binding on error code */ public void setSkipBindingOnErrorCode(boolean skipBindingOnErrorCode) { this.skipBindingOnErrorCode = skipBindingOnErrorCode; } public boolean isClientRequestValidation() { return clientRequestValidation; } /** * Whether to enable validation of the client request to check whether the Content-Type and Accept headers from * the client is supported by the Rest-DSL configuration of its consumes/produces settings. * * This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. * * The default value is false. */ public void setClientRequestValidation(boolean clientRequestValidation) { this.clientRequestValidation = clientRequestValidation; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @return whether CORS is enabled or not */ public boolean isEnableCORS() { return enableCORS; } /** * To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. * * This option is default false * * @param enableCORS true to enable CORS */ public void setEnableCORS(boolean enableCORS) { this.enableCORS = enableCORS; } /** * Gets the name of the json data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getJsonDataFormat() { return jsonDataFormat; } /** * Sets a custom json data format to be used * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setJsonDataFormat(String name) { this.jsonDataFormat = name; } /** * Gets the name of the xml data format. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @return the name, or null to use default */ public String getXmlDataFormat() { return xmlDataFormat; } /** * Sets a custom xml data format to be used. * * Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. * * @param name name of the data format */ public void setXmlDataFormat(String name) { this.xmlDataFormat = name; } /** * Gets additional options on component level * * @return additional options */ public Map getComponentProperties() { return componentProperties; } /** * Sets additional options on component level * * @param componentProperties the options */ public void setComponentProperties(Map componentProperties) { this.componentProperties = componentProperties; } /** * Gets additional options on endpoint level * * @return additional options */ public Map getEndpointProperties() { return endpointProperties; } /** * Sets additional options on endpoint level * * @param endpointProperties the options */ public void setEndpointProperties(Map endpointProperties) { this.endpointProperties = endpointProperties; } /** * Gets additional options on consumer level * * @return additional options */ public Map getConsumerProperties() { return consumerProperties; } /** * Sets additional options on consumer level * * @param consumerProperties the options */ public void setConsumerProperties(Map consumerProperties) { this.consumerProperties = consumerProperties; } /** * Gets additional options on data format level * * @return additional options */ public Map getDataFormatProperties() { return dataFormatProperties; } /** * Sets additional options on data format level * * @param dataFormatProperties the options */ public void setDataFormatProperties(Map dataFormatProperties) { this.dataFormatProperties = dataFormatProperties; } public Map getApiProperties() { return apiProperties; } /** * Sets additional options on api level * * @param apiProperties the options */ public void setApiProperties(Map apiProperties) { this.apiProperties = apiProperties; } /** * Gets the CORS headers to use if CORS has been enabled. * * @return the CORS headers */ public Map getCorsHeaders() { return corsHeaders; } /** * Sets the CORS headers to use if CORS has been enabled. * * @param corsHeaders the CORS headers */ public void setCorsHeaders(Map corsHeaders) { this.corsHeaders = corsHeaders; } } |
data class | 1. data class | t | t | t | 0 | 11514 | https://github.com/apache/camel/blob/8a85a70643c4d6eec2d3abddeea44ecb06c2f486/core/camel-api/src/main/java/org/apache/camel/spi/RestConfiguration.java/#L25-L585 | 1 | 1633 | 11514 | critical | ||
| 5515 | {"response": "YES I found bad smells", "bad smells are": ["Long method", "Magic number", "Non-descriptive method or variable names", "Nested block", "Complex conditional logic", "Duplicate code"]} | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @SuppressWarnings("try") private void doRun(Map entryPoints, Method mainEntryPoint, JavaMainSupport javaMainSupport, String imageName, AbstractBootImage.NativeImageKind k, SubstitutionProcessor harnessSubstitutions, ForkJoinPool compilationExecutor, ForkJoinPool analysisExecutor) { List hostedEntryPoints = new ArrayList<>(); OptionValues options = HostedOptionValues.singleton(); SnippetReflectionProvider originalSnippetReflection = GraalAccess.getOriginalSnippetReflection(); try (DebugContext debug = DebugContext.create(options, new GraalDebugHandlersFactory(originalSnippetReflection))) { setupNativeImage(imageName, options, entryPoints, javaMainSupport, harnessSubstitutions, analysisExecutor, originalSnippetReflection, debug); boolean returnAfterAnalysis = runPointsToAnalysis(imageName, options, debug); if (returnAfterAnalysis) { return; } NativeImageHeap heap; HostedMethod mainEntryPointHostedStub; HostedMetaAccess hMetaAccess; SharedRuntimeConfigurationBuilder runtime; try (StopTimer t = new Timer(imageName, "universe").start()) { hUniverse = new HostedUniverse(bigbang); hMetaAccess = new HostedMetaAccess(hUniverse, bigbang.getMetaAccess()); new UniverseBuilder(aUniverse, bigbang.getMetaAccess(), hUniverse, hMetaAccess, HostedConfiguration.instance().createStaticAnalysisResultsBuilder(bigbang, hUniverse), bigbang.getUnsupportedFeatures()).build(debug); runtime = new HostedRuntimeConfigurationBuilder(options, bigbang.getHostVM(), hUniverse, hMetaAccess, bigbang.getProviders()).build(); registerGraphBuilderPlugins(featureHandler, runtime.getRuntimeConfig(), (HostedProviders) runtime.getRuntimeConfig().getProviders(), bigbang.getMetaAccess(), aUniverse, hMetaAccess, hUniverse, nativeLibraries, loader, false, true, bigbang.getAnnotationSubstitutionProcessor(), new SubstrateClassInitializationPlugin((SVMHost) aUniverse.hostVM()), bigbang.getHostVM().getClassInitializationSupport()); if (NativeImageOptions.PrintUniverse.getValue()) { printTypes(); } /* Find the entry point methods in the hosted world. */ for (AnalysisMethod m : aUniverse.getMethods()) { if (m.isEntryPoint()) { HostedMethod found = hUniverse.lookup(m); assert found != null; hostedEntryPoints.add(found); } } /* Find main entry point */ if (mainEntryPoint != null) { AnalysisMethod analysisStub = CEntryPointCallStubSupport.singleton().getStubForMethod(mainEntryPoint); mainEntryPointHostedStub = (HostedMethod) hMetaAccess.getUniverse().lookup(analysisStub); assert hostedEntryPoints.contains(mainEntryPointHostedStub); } else { mainEntryPointHostedStub = null; } if (hostedEntryPoints.size() == 0) { throw UserError.abort("Warning: no entry points found, i.e., no method annotated with @" + CEntryPoint.class.getSimpleName()); } heap = new NativeImageHeap(aUniverse, hUniverse, hMetaAccess); BeforeCompilationAccessImpl config = new BeforeCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.beforeCompilation(config)); bigbang.getUnsupportedFeatures().report(bigbang); } catch (UnsupportedFeatureException ufe) { throw UserError.abort(ufe.getMessage()); } recordMethodsWithStackValues(); recordRestrictHeapAccessCallees(aUniverse.getMethods()); /* * After this point, all TypeFlow (and therefore also TypeState) objects are unreachable * and can be garbage collected. This is important to keep the overall memory footprint * low. However, this also means we no longer have complete call chain information. Only * the summarized information stored in the StaticAnalysisResult objects is available * after this point. */ bigbang.cleanupAfterAnalysis(); NativeImageCodeCache codeCache; CompileQueue compileQueue; try (StopTimer t = new Timer(imageName, "compile").start()) { compileQueue = HostedConfiguration.instance().createCompileQueue(debug, featureHandler, hUniverse, runtime, DeoptTester.enabled(), bigbang.getProviders().getSnippetReflection(), compilationExecutor); compileQueue.finish(debug); /* release memory taken by graphs for the image writing */ hUniverse.getMethods().forEach(HostedMethod::clear); codeCache = NativeImageCodeCacheFactory.get().newCodeCache(compileQueue, heap); codeCache.layoutConstants(); codeCache.layoutMethods(debug, imageName); AfterCompilationAccessImpl config = new AfterCompilationAccessImpl(featureHandler, loader, aUniverse, hUniverse, hMetaAccess, heap, debug); featureHandler.forEachFeature(feature -> feature.afterCompilation(config)); } try (Indent indent = debug.logAndIndent("create native image")) { try (DebugContext.Scope buildScope = debug.scope("CreateBootImage")) { try (StopTimer t = new Timer(imageName, "image").start()) { // Start building the model of the native image heap. heap.addInitialObjects(); // Then build the model of the code cache, which can // add objects to the native image heap. codeCache.addConstantsToHeap(); // Finish building the model of the native image heap. heap.addTrailingObjects(); AfterHeapLayoutAccessImpl config = new AfterHeapLayoutAccessImpl(featureHandler, loader, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.afterHeapLayout(config)); this.image = AbstractBootImage.create(k, hUniverse, hMetaAccess, nativeLibraries, heap, codeCache, hostedEntryPoints, mainEntryPointHostedStub, loader.getClassLoader()); image.build(debug); if (NativeImageOptions.PrintUniverse.getValue()) { /* * This debug output must be printed _after_ and not _during_ image * building, because it adds some PrintStream objects to static fields, * which disrupts the heap. */ codeCache.printCompilationResults(); } } } } BeforeImageWriteAccessImpl beforeConfig = new BeforeImageWriteAccessImpl(featureHandler, loader, imageName, image, runtime.getRuntimeConfig(), aUniverse, hUniverse, optionProvider, hMetaAccess, debug); featureHandler.forEachFeature(feature -> feature.beforeImageWrite(beforeConfig)); try (StopTimer t = new Timer(imageName, "write").start()) { /* * This will write the debug info too -- i.e. we may be writing more than one file, * if the debug info is in a separate file. We need to push writing the file to the * image implementation, because whether the debug info and image share a file or * not is an implementation detail of the image. */ Path tmpDir = tempDirectory(); Path imagePath = image.write(debug, generatedFiles(HostedOptionValues.singleton()), tmpDir, imageName, beforeConfig).getOutputFile(); AfterImageWriteAccessImpl afterConfig = new AfterImageWriteAccessImpl(featureHandler, loader, hUniverse, imagePath, tmpDir, image.getBootImageKind(), debug); featureHandler.forEachFeature(feature -> feature.afterImageWrite(afterConfig)); } } } |
long method | long method, magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | t | t | t | magic number, non-descriptive method or variable names, nested block, complex conditional logic, duplicate code | 0 | 4260 | https://github.com/oracle/graal/blob/4deb681aaaa79c248115037fc8e399c9876619fd/substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/NativeImageGenerator.java/#L487-L632 | 2 | 5515 | 4260 | critical | |
| 2309 | { "message": "YES I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: NativeKeyHolder(P11Key p11Key, long keyID, Session keySession, boolean extractKeyInfo, boolean isTokenObject) { this.p11Key = p11Key; this.keyID = keyID; this.refCount = -1; byte[] ki = null; if (isTokenObject) { this.ref = null; } else { this.ref = new SessionKeyRef(p11Key, keyID, keySession); // Try extracting key info, if any error, disable it Token token = p11Key.token; if (extractKeyInfo) { try { if (p11Key.sensitive && nativeKeyWrapperKeyID == 0) { synchronized(NativeKeyHolder.class) { // Create a global wrapping/unwrapping key CK_ATTRIBUTE[] wrappingAttributes = token.getAttributes (O_GENERATE, CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY), new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3), }); Session wrappingSession = null; try { wrappingSession = token.getObjSession(); nativeKeyWrapperKeyID = token.p11.C_GenerateKey (wrappingSession.id(), new CK_MECHANISM(CKM_AES_KEY_GEN), wrappingAttributes); byte[] iv = new byte[16]; JCAUtil.getSecureRandom().nextBytes(iv); nativeKeyWrapperMechanism = new CK_MECHANISM (CKM_AES_CBC_PAD, iv); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(wrappingSession); } } } Session opSession = null; try { opSession = token.getOpSession(); ki = p11Key.token.p11.getNativeKeyInfo(opSession.id(), keyID, nativeKeyWrapperKeyID, nativeKeyWrapperMechanism); } catch (PKCS11Exception e) { // best effort } finally { token.releaseSession(opSession); } } catch (PKCS11Exception e) { // best effort } } } this.nativeKeyInfo = ((ki == null || ki.length == 0)? null : ki); } |
long method | long method | t | t | t | 0 | 14095 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java/#L1154-L1211 | 1 | 2309 | 14095 | minor | ||
| 2378 | { "response": "YES I found bad smells", "detected_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: static class Cause { final Tuple tuple ; final Mapping mapping ; public Cause(Tuple tuple, Mapping mapping) { super() ; this.tuple = tuple ; this.mapping = mapping ; } } |
data class | blob, data class | t | t | t | blob | 0 | 14333 | https://github.com/apache/jena/blob/1cca775bbf0bb0fd3ee8ac55e31f0f30cdde3b77/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java/#L113-L122 | 1 | 2378 | 14333 | minor | |
| 1052 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Application { private String name; private Map inputs; public Application() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } } |
data class | data class | t | t | t | 0 | 9479 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/test-suite/multi-tenanted-airavata/src/main/java/org/apache/airavata/testsuite/multitenantedairavata/TestFrameworkProps.java/#L199-L221 | 1 | 1052 | 9479 | minor | ||
| 3707 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Future monitorUntil(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Function0 isFinished) { Future _xblockexpression = null; { final Runnable _function = () -> { try { while ((!(isFinished.apply()).booleanValue())) { { boolean _isCanceled = cancelIndicator.isCanceled(); if (_isCanceled) { CompilationUnitImpl _compilationUnit = ctx.getCompilationUnit(); _compilationUnit.setCanceled(true); return; } Thread.sleep(100); } } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }; final Runnable r = _function; Future _xtrycatchfinallyexpression = null; try { _xtrycatchfinallyexpression = this.pool.submit(r); } catch (final Throwable _t) { if (_t instanceof RejectedExecutionException) { final RejectedExecutionException e = (RejectedExecutionException)_t; AnnotationProcessor.CancellationObserver.log.debug(e.getMessage(), e); new Thread(r).start(); } else { throw Exceptions.sneakyThrow(_t); } } _xblockexpression = _xtrycatchfinallyexpression; } return _xblockexpression; } |
long method | 1. long method, 2. data class | t | t | t | 2. data class | 0 | 8853 | https://github.com/eclipse/xtext-xtend/blob/20500a324127e3ee73cb793a13430ee140246fa7/org.eclipse.xtend.core/xtend-gen/org/eclipse/xtend/core/macro/AnnotationProcessor.java/#L69-L105 | 1 | 3707 | 8853 | minor | |
| 752 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: else { fstack.add(cfkey); builder.append(offset + "--" + cfkey + "\n"); builder.append(explainFunctionCallGraph(fgraph, fstack, cfkey, level+1)); fstack.remove(cfkey); } } } return builder.toString(); } } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 7035 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/utils/Explain.java/#L1103-L1141 | 1 | 752 | 7035 | major | |
| 2396 | YES I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14374 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 2 | 2396 | 14374 | minor | ||
| 674 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ClearCacheResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; unfreedBytes_ = input.readInt64(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } |
long method | long method | t | t | t | 0 | 6568 | https://github.com/apache/phoenix/blob/69e5bb0b304a53967cef40b2a4cfc66e69ecaa51/phoenix-core/src/main/java/org/apache/phoenix/coprocessor/generated/MetaDataProtos.java/#L13962-L14001 | 1 | 674 | 6568 | minor | ||
| 2265 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public interface ReplicatedLevelDBStoreViewMBean { @MBeanInfo("The address of the ZooKeeper server.") String getZkAddress(); @MBeanInfo("The path in ZooKeeper to hold master elections.") String getZkPath(); @MBeanInfo("The ZooKeeper session timeout.") String getZkSessionTimeout(); @MBeanInfo("The address and port the master will bind for the replication protocol.") String getBind(); @MBeanInfo("The number of replication nodes that will be part of the replication cluster.") int getReplicas(); @MBeanInfo("The role of this node in the replication cluster.") String getNodeRole(); @MBeanInfo("The replication status.") String getStatus(); @MBeanInfo("The status of the connected slaves.") CompositeData[] getSlaves(); @MBeanInfo("The current position of the replication log.") Long getPosition(); @MBeanInfo("When the last entry was added to the replication log.") Long getPositionDate(); @MBeanInfo("The directory holding the data.") String getDirectory(); @MBeanInfo("The sync strategy to use.") String getSync(); @MBeanInfo("The node id of this replication node.") String getNodeId(); } |
data class | data class | t | t | t | 0 | 13729 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-leveldb-store/src/main/java/org/apache/activemq/leveldb/replicated/ReplicatedLevelDBStoreViewMBean.java/#L30-L66 | 1 | 2265 | 13729 | major | ||
| 2759 | YES I found bad smells the bad smells are: Long method, Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private BundleEvent initializeEvent(Bundle bundle) { switch (bundle.getState()) { case Bundle.INSTALLED: return new BundleEvent(BundleEvent.INSTALLED, bundle); case Bundle.RESOLVED: return new BundleEvent(BundleEvent.RESOLVED, bundle); default: return new BundleEvent(BundleEvent.STARTED, bundle); } } |
feature envy | Long method, Feature envy | t | f | t | Long method | 0 | 874 | https://github.com/eclipse/smarthome/blob/b8455de15d65512e8fac4e94d42de6ab2fccf1c5/bundles/automation/org.eclipse.smarthome.automation.providers/src/main/java/org/eclipse/smarthome/automation/internal/core/provider/AutomationResourceBundlesTracker.java/#L278-L287 | 2 | 2759 | 874 | minor | |
| 1826 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static void initialize() { STRAM.setChildren(Sets.newHashSet(APPLICATION, TEMPLATE)); APPLICATION.setChildren(Sets.newHashSet(GATEWAY, OPERATOR, STREAM)); OPERATOR.setChildren(Sets.newHashSet(PORT)); PORT.setChildren(Sets.newHashSet(UNIFIER)); STRAM_ELEMENT_TO_CONF_ELEMENT.clear(); //Initialize StramElement to ConfElement for (ConfElement confElement: ConfElement.values()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(confElement.getStramElement(), confElement); for (StramElement sElement: confElement.getAllRelatedElements()) { STRAM_ELEMENT_TO_CONF_ELEMENT.put(sElement, confElement); } } //Initialize attributes for (ConfElement confElement: ConfElement.values()) { if (confElement.getParent() == null) { continue; } setAmbiguousAttributes(confElement); } // build context to conf element map CONTEXT_TO_CONF_ELEMENT.clear(); for (ConfElement confElement: ConfElement.values()) { CONTEXT_TO_CONF_ELEMENT.put(confElement.getContextClass(), confElement); } //Check if all the context classes are accounted for Set> confElementContextClasses = Sets.newHashSet(); for (ConfElement confElement: ConfElement.values()) { if (confElement.getContextClass() == null) { continue; } confElementContextClasses.add(confElement.getContextClass()); } if (!ContextUtils.CONTEXT_CLASSES.equals(confElementContextClasses)) { throw new IllegalStateException("All the context classes " + ContextUtils.CONTEXT_CLASSES + " found in " + Context.class + " are not used by ConfElements " + confElementContextClasses); } } |
long method | Long Method, Data Class | t | f | t | Data Class | 0 | 12112 | https://github.com/apache/apex-core/blob/d17f464fcaf19778e2f8edbe2b03419151558068/engine/src/main/java/com/datatorrent/stram/plan/logical/LogicalPlanConfiguration.java/#L230-L279 | 1 | 1826 | 12112 | minor | |
| 2274 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy | 0 | 13771 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 2 | 2274 | 13771 | major | |
| 3849 | * values of the calendar fields. * YES I found bad smells the bad smells are: 1. Magic numbers 2. Long method 3. Feature envy 4. Inconsistent variable naming | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: int year = gc.cdate.getNormalizedYear(); if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) { long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate)); BaseCalendar.Date d = getCalendarDate(month1); return d.getDayOfMonth(); } } return getMinimum(field); } /** * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current |
feature envy | Magic numbers2 Long method3 Feature envy4 Inconsistent variable naming | t | f | t | 0 | 9990 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java/#L1674-L1686 | 2 | 3849 | 9990 | minor | ||
| 1841 | YES, I found bad smells. The bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public SystemDiagnosticsDTO createSystemDiagnosticsDto(final SystemDiagnostics sysDiagnostics) { final SystemDiagnosticsDTO dto = new SystemDiagnosticsDTO(); final SystemDiagnosticsSnapshotDTO snapshot = new SystemDiagnosticsSnapshotDTO(); dto.setAggregateSnapshot(snapshot); snapshot.setStatsLastRefreshed(new Date(sysDiagnostics.getCreationTimestamp())); // processors snapshot.setAvailableProcessors(sysDiagnostics.getAvailableProcessors()); snapshot.setProcessorLoadAverage(sysDiagnostics.getProcessorLoadAverage()); // threads snapshot.setDaemonThreads(sysDiagnostics.getDaemonThreads()); snapshot.setTotalThreads(sysDiagnostics.getTotalThreads()); // heap snapshot.setMaxHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxHeap())); snapshot.setMaxHeapBytes(sysDiagnostics.getMaxHeap()); snapshot.setTotalHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalHeap())); snapshot.setTotalHeapBytes(sysDiagnostics.getTotalHeap()); snapshot.setUsedHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedHeap())); snapshot.setUsedHeapBytes(sysDiagnostics.getUsedHeap()); snapshot.setFreeHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeHeap())); snapshot.setFreeHeapBytes(sysDiagnostics.getFreeHeap()); if (sysDiagnostics.getHeapUtilization() != -1) { snapshot.setHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getHeapUtilization())); } // non heap snapshot.setMaxNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getMaxNonHeap())); snapshot.setMaxNonHeapBytes(sysDiagnostics.getMaxNonHeap()); snapshot.setTotalNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getTotalNonHeap())); snapshot.setTotalNonHeapBytes(sysDiagnostics.getTotalNonHeap()); snapshot.setUsedNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getUsedNonHeap())); snapshot.setUsedNonHeapBytes(sysDiagnostics.getUsedNonHeap()); snapshot.setFreeNonHeap(FormatUtils.formatDataSize(sysDiagnostics.getFreeNonHeap())); snapshot.setFreeNonHeapBytes(sysDiagnostics.getFreeNonHeap()); if (sysDiagnostics.getNonHeapUtilization() != -1) { snapshot.setNonHeapUtilization(FormatUtils.formatUtilization(sysDiagnostics.getNonHeapUtilization())); } // flow file disk usage final SystemDiagnosticsSnapshotDTO.StorageUsageDTO flowFileRepositoryStorageUsageDto = createStorageUsageDTO(null, sysDiagnostics.getFlowFileRepositoryStorageUsage()); snapshot.setFlowFileRepositoryStorageUsage(flowFileRepositoryStorageUsageDto); // content disk usage final Set contentRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setContentRepositoryStorageUsage(contentRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getContentRepositoryStorageUsage().entrySet()) { contentRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // provenance disk usage final Set provenanceRepositoryStorageUsageDtos = new LinkedHashSet<>(); snapshot.setProvenanceRepositoryStorageUsage(provenanceRepositoryStorageUsageDtos); for (final Map.Entry entry : sysDiagnostics.getProvenanceRepositoryStorageUsage().entrySet()) { provenanceRepositoryStorageUsageDtos.add(createStorageUsageDTO(entry.getKey(), entry.getValue())); } // garbage collection final Set garbageCollectionDtos = new LinkedHashSet<>(); snapshot.setGarbageCollection(garbageCollectionDtos); for (final Map.Entry entry : sysDiagnostics.getGarbageCollection().entrySet()) { garbageCollectionDtos.add(createGarbageCollectionDTO(entry.getKey(), entry.getValue())); } // version info final SystemDiagnosticsSnapshotDTO.VersionInfoDTO versionInfoDto = createVersionInfoDTO(); snapshot.setVersionInfo(versionInfoDto); // uptime snapshot.setUptime(FormatUtils.formatHoursMinutesSeconds(sysDiagnostics.getUptime(), TimeUnit.MILLISECONDS)); return dto; } |
feature envy | Long method 2 Feature envy | t | f | t | 0 | 12150 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java/#L3110-L3185 | 2 | 1841 | 12150 | critical | ||
| 360 | { "response": "YES I found bad smells", "detected_bad_smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class User { private String name = "nameA"; private int age = 100; private int index; private String[] names; public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getNames() { return names; } public void setNames(String[] names) { this.names = names; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public String jsonString() { try { return JsonUtils.writeValueAsString(this); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } } |
data class | data class | t | t | t | 0 | 3696 | https://github.com/apache/servicecomb-java-chassis/blob/72cd0e137c4a0c3b899adfa6e19e2fd590743014/integration-tests/it-common/src/main/java/org/apache/servicecomb/it/schema/User.java/#L23-L76 | 1 | 360 | 3696 | minor | ||
| 790 | { "response": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer1149 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer1149() {} public Customer1149(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer1149[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 7527 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer1149.java/#L8-L27 | 1 | 790 | 7527 | major | ||
| 356 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Value public class Release { private final String id; private final ProjectKey projectKey; private final String name; private final String description; private final LocalDate date; } |
data class | blob, data class | t | t | t | blob | 0 | 3676 | https://github.com/spring-projects/spring-data-dev-tools/blob/a25ff3ae28026f132871f7172c6ba5c3b64e1671/release-tools/src/main/java/org/springframework/data/release/model/Release.java/#L25-L33 | 1 | 356 | 3676 | major | |
| 935 | {"response": "YES I found bad smells. the bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public boolean matchesAllInstances(SequenceType testST) { Quantifier stq = sequenceType.getQuantifier(); ItemType it = sequenceType.getItemType(); if (stq.isSubQuantifier(testST.getQuantifier())) { if (it instanceof AnyItemType) { return true; } else if (it.isAtomicType() && testST.getItemType().isAtomicType()) { AtomicType ait = (AtomicType) it; AtomicType testIT = (AtomicType) testST.getItemType(); if (BuiltinTypeRegistry.INSTANCE.isBuiltinTypeId(testIT.getTypeId())) { SchemaType vType = BuiltinTypeRegistry.INSTANCE.getSchemaTypeById(testIT.getTypeId()); while (vType != null && vType.getTypeId() != ait.getTypeId()) { vType = vType.getBaseType(); } return vType != null; } } else if (it instanceof NodeType && testST.getItemType() instanceof NodeType) { NodeType nt = (NodeType) it; NodeKind kind = nt.getNodeKind(); NodeType testNT = (NodeType) testST.getItemType(); NodeKind testKind = testNT.getNodeKind(); if (kind == NodeKind.ANY || kind == testKind) { return true; } } return false; } return false; } |
long method | 1. long method | t | t | t | 0 | 8393 | https://github.com/apache/vxquery/blob/5d1175d2cb04a54ba751295f2ac67daec38bf723/vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/type/SequenceTypeMatcher.java/#L156-L184 | 1 | 935 | 8393 | minor | ||
| 1884 | YES I found bad smells The bad smells are: 1. Long method 2. Feature Envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean isExists(Object identifier) throws AppCatalogException { HashMap ids; if (identifier instanceof Map) { ids = (HashMap) identifier; } else { logger.error("Identifier should be a map with the field name and it's value"); throw new AppCatalogException("Identifier should be a map with the field name and it's value"); } EntityManager em = null; try { em = AppCatalogJPAUtils.getEntityManager(); ComputeResourcePreference existingPreference = em.find(ComputeResourcePreference.class, new ComputeResourcePreferencePK(ids.get(ComputeResourcePreferenceConstants.GATEWAY_ID), ids.get(ComputeResourcePreferenceConstants.RESOURCE_ID))); if (em.isOpen()) { if (em.getTransaction().isActive()){ em.getTransaction().rollback(); } em.close(); } return existingPreference != null; }catch (Exception e) { logger.error(e.getMessage(), e); throw new AppCatalogException(e); } finally { if (em != null && em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } } |
feature envy | Long method2 Feature Envy | t | f | t | 0 | 12292 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/app/catalog/resources/ComputeHostPreferenceResource.java/#L522-L556 | 2 | 1884 | 12292 | minor | ||
| 1942 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private ApplicationDTO buildApplicationDTO( ApplicationRuntimeInformation ari) { ApplicationDTO applicationDTO = new ApplicationDTO(){}; applicationDTO.name = getServiceName( ari._cachingServiceReference::getProperty); applicationDTO.base = _whiteboard.getApplicationBase( ari._cachingServiceReference::getProperty); applicationDTO.serviceId = (Long)ari._cachingServiceReference.getProperty("service.id"); applicationDTO.resourceDTOs = getApplicationEndpointsStream( applicationDTO.name).toArray( ResourceDTO[]::new ); applicationDTO.extensionDTOs = getApplicationExtensionsStream( applicationDTO.name).toArray( ExtensionDTO[]::new ); Map> nameBoundExtensions = new HashMap<>(); Map> extensionResources = new HashMap<>(); for (ExtensionDTO extensionDTO : applicationDTO.extensionDTOs) { if (extensionDTO.nameBindings == null) { continue; } for (String nameBinding : extensionDTO.nameBindings) { Set extensionDTOS = nameBoundExtensions.computeIfAbsent( nameBinding, __ -> new HashSet<>() ); extensionDTOS.add(extensionDTO); } } for (ResourceDTO resourceDTO : applicationDTO.resourceDTOs) { for (ResourceMethodInfoDTO resourceMethodInfo : resourceDTO.resourceMethods) { if (resourceMethodInfo.nameBindings == null) { continue; } for (String nameBinding : resourceMethodInfo.nameBindings) { Set extensionDTOS = nameBoundExtensions.get( nameBinding); if (extensionDTOS != null) { for (ExtensionDTO extensionDTO : extensionDTOS) { Set resourceDTOS = extensionResources.computeIfAbsent( extensionDTO, __ -> new HashSet<>()); resourceDTOS.add(resourceDTO); } } } } } extensionResources.forEach( (extensionDTO, resourceDTOS) -> extensionDTO.filteredByName = resourceDTOS.toArray( new ResourceDTO[0]) ); CxfJaxrsServiceRegistrator cxfJaxRsServiceRegistrator = ari._cxfJaxRsServiceRegistrator; Bus bus = cxfJaxRsServiceRegistrator.getBus(); Iterable> resourceClasses = cxfJaxRsServiceRegistrator.getStaticResourceClasses(); ArrayList resourceMethodInfoDTOS = new ArrayList<>(); for (Class resourceClass : resourceClasses) { resourceMethodInfoDTOS.addAll( ClassIntrospector.getResourceMethodInfos(resourceClass, bus)); } applicationDTO.resourceMethods = resourceMethodInfoDTOS.toArray( new ResourceMethodInfoDTO[0]); return applicationDTO; } |
long method | long method, data class | t | t | t | data class | 0 | 12499 | https://github.com/apache/aries-jax-rs-whiteboard/blob/73ef94bb74159e97bbe834c3e17a7eb3c34b7bf6/jax-rs.whiteboard/src/main/java/org/apache/aries/jax/rs/whiteboard/internal/AriesJaxrsServiceRuntime.java/#L943-L1037 | 1 | 1942 | 12499 | major | |
| 701 | {"message": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | long method, blob | t | t | t | blob | 0 | 6688 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 701 | 6688 | major | |
| 4205 | YES I found bad smells. The bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class loadClass2(String className, Class callingClass) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException ex) { try { if (ClassLoaderUtils.class.getClassLoader() != null) { return ClassLoaderUtils.class.getClassLoader().loadClass(className); } } catch (ClassNotFoundException exc) { if (callingClass != null && callingClass.getClassLoader() != null) { return callingClass.getClassLoader().loadClass(className); } } LOG.debug(ex.getMessage(), ex); throw ex; } } |
long method | Long method, 2 Feature envy | t | f | t | 2. Feature envy. | 0 | 11065 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java/#L66-L83 | 2 | 4205 | 11065 | minor | |
| 642 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 6353 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 642 | 6353 | critical | ||
| 1544 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | Long method 2 Feature envy | t | f | t | 0 | 11245 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 2 | 1544 | 11245 | minor | ||
| 597 | {"response": "YES I found bad smells the bad smells are: Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class GetOperationCompletedEvent extends OperationCompletedEvent { private final GetRequest[] requests; private final GetStatus status; public GetOperationCompletedEvent( final EventSource source, final Workspace workspace, final GetRequest[] requests, final GetStatus status) { super(source, workspace, ProcessType.GET); Check.notNull(requests, "requests"); //$NON-NLS-1$ this.requests = requests; this.status = status; } /** * @return the status object produced by the get operation that caused this * event. null means the get operation did not fully complete. */ public GetStatus getStatus() { return status; } /** * @return the request objects that initiated this get operation. */ public GetRequest[] getRequests() { return requests; } } |
data class | data class | t | t | t | 0 | 5956 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/events/GetOperationCompletedEvent.java/#L17-L48 | 1 | 597 | 5956 | major | ||
| 1179 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public Object doExecute() throws Exception { Group group = groupManager.findGroupByName(groupName); if (group == null) { System.err.println("Cluster group " + groupName + " doesn't exist"); return null; } CellarSupport support = new CellarSupport(); support.setClusterManager(clusterManager); support.setGroupManager(groupManager); support.setConfigurationAdmin(configurationAdmin); if (!in && !out) { in = true; out = true; } if (!whitelist && !blacklist) { whitelist = true; blacklist = true; } if (pid == null || pid.isEmpty()) { // display mode if (in) { System.out.println("INBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND); System.out.println(list.toString()); } } if (out) { System.out.println("OUTBOUND:"); if (whitelist) { System.out.print("\twhitelist: "); Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } if (blacklist) { System.out.print("\tblacklist: "); Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND); System.out.println(list.toString()); } } } else { // edit mode System.out.println("Updating blocking policy for " + pid); if (in) { if (whitelist) { System.out.println("\tinbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } if (blacklist) { System.out.println("\tinbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid); } } if (out) { if (whitelist) { System.out.println("\toutbound whitelist ..."); support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } if (blacklist) { System.out.println("\toutbound blacklist ..."); support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid); } } } return null; } |
long method | long method, feature envy | t | t | t | feature envy | 0 | 10227 | https://github.com/apache/karaf-cellar/blob/4082b26110e56973dceb2563395f8aed3f294dd1/config/src/main/java/org/apache/karaf/cellar/config/shell/BlockCommand.java/#L56-L132 | 1 | 1179 | 10227 | critical | |
| 2327 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public List discoverHosts(final AddHostCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { Long dcId = cmd.getZoneId(); final Long podId = cmd.getPodId(); final Long clusterId = cmd.getClusterId(); String clusterName = cmd.getClusterName(); final String url = cmd.getUrl(); final String username = cmd.getUsername(); final String password = cmd.getPassword(); final List hostTags = cmd.getHostTags(); dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId); // this is for standalone option if (clusterName == null && clusterId == null) { clusterName = "Standalone-" + url; } if (clusterId != null) { final ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { final InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); ex.addProxyObject(clusterId.toString(), "clusterId"); throw ex; } else { if (cluster.getGuid() == null) { final List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { final CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); ex.addProxyObject(cluster.getUuid(), "clusterId"); throw ex; } } } } return discoverHostsFull(dcId, podId, clusterId, clusterName, url, username, password, cmd.getHypervisor(), hostTags, cmd.getFullUrlParams(), false); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 14144 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java/#L573-L611 | 2 | 2327 | 14144 | minor | |
| 1587 | YES I found bad smells the bad smells are: 1. Feature envy 2. Long method 3. Code duplication 4. Lack of comments/documentation 5. Poor variable naming/descriptive names 6. Code that is difficult to understand/maintain 7. Potential violation of single responsibility principle 8. Potential catch-all exception handling. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static void registerConfigOptions(IConfigManager configManager) { AsterixProperties.registerConfigOptions(configManager); ControllerConfig.Option.DEFAULT_DIR .setDefaultValue(FileUtil.joinPath(System.getProperty(ConfigurationUtil.JAVA_IO_TMPDIR), "asterixdb")); NCConfig.Option.APP_CLASS.setDefaultValue(NCApplication.class.getName()); CCConfig.Option.APP_CLASS.setDefaultValue(CCApplication.class.getName()); try { InputStream propertyStream = ApplicationConfigurator.class.getClassLoader().getResourceAsStream("git.properties"); if (propertyStream != null) { Properties gitProperties = new Properties(); gitProperties.load(propertyStream); StringWriter sw = new StringWriter(); gitProperties.store(sw, null); configManager.setVersionString(sw.toString()); } } catch (IOException e) { throw new IllegalStateException(e); } } |
long method | Feature envy2 Long method3 Code duplication4 Lack of comments/documentation5 Poor variable naming/descriptive names6 Code that is difficult to understand/maintain7 Potential violation of single responsibility principle 8 Potential catch-all exception handling | t | f | t | 0 | 11373 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-app/src/main/java/org/apache/asterix/hyracks/bootstrap/ApplicationConfigurator.java/#L45-L65 | 2 | 1587 | 11373 | minor | ||
| 2089 | { "message": "YES I found bad smells", "detected_bad_smells": [ "1. Blob", "2. Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the source and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx instruction with // IFNOTxxx GOTO_W , where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // with IFNOTxxx GOTO_W , where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // recomputes the stack map frames if (frameCount > 0) { if (compute == FRAMES) { frameCount = 0; stackMap = null; previousFrame = null; frame = null; Frame f = new Frame(); f.owner = labels; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, maxLocals); visitFrame(f); Label l = labels; while (l != null) { /* * here we need the original label position. getNewOffset * must therefore never have been called for this label. */ u = l.position - 3; if ((l.status & Label.STORE) != 0 || (u >= 0 && resize[u])) { getNewOffset(allIndexes, allSizes, l); // TODO update offsets in UNINITIALIZED values visitFrame(l.frame); } l = l.successor; } } else { /* * Resizing an existing stack map frame table is really hard. * Not only the table must be parsed to update the offets, but * new frames may be needed for jump instructions that were * inserted by this method. And updating the offsets or * inserting frames can change the format of the following * frames, in case of packed frames. In practice the whole table * must be recomputed. For this the frames are marked as * potentially invalid. This will cause the whole class to be * reread and rewritten with the COMPUTE_FRAMES option (see the * ClassWriter.toByteArray method). This is not very efficient * but is much easier and requires much less code than any other * method I can think of. */ cw.invalidFrames = true; } } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } |
long method | 1. blob, 2. long method | t | t | t | 1. blob | 0 | 13117 | https://github.com/apache/tajo/blob/fb326195083959014c82c10187cb46de91ece33f/tajo-thirdparty/asm/src/main/java/org/apache/tajo/org/objectweb/asm/MethodWriter.java/#L2145-L2559 | 1 | 2089 | 13117 | major | |
| 3412 | YES I found bad smells the bad smells are: 1. Long method 2. Magic numbers 3. Hard-coded strings 4. Code duplication | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public final void mRULE_ML_COMMENT() throws RecognitionException { try { int _type = RULE_ML_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalCrossReferenceProposalTestLanguage.g:169:17: ( '/*' ( options {greedy=false; } : . )* '*/' ) // InternalCrossReferenceProposalTestLanguage.g:169:19: '/*' ( options {greedy=false; } : . )* '*/' { match("/*"); // InternalCrossReferenceProposalTestLanguage.g:169:24: ( options {greedy=false; } : . )* loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0=='*') ) { int LA7_1 = input.LA(2); if ( (LA7_1=='/') ) { alt7=2; } else if ( ((LA7_1>='\u0000' && LA7_1<='.')||(LA7_1>='0' && LA7_1<='\uFFFF')) ) { alt7=1; } } else if ( ((LA7_0>='\u0000' && LA7_0<=')')||(LA7_0>='+' && LA7_0<='\uFFFF')) ) { alt7=1; } switch (alt7) { case 1 : // InternalCrossReferenceProposalTestLanguage.g:169:52: . { matchAny(); } break; default : break loop7; } } while (true); match("*/"); } state.type = _type; state.channel = _channel; } finally { } } |
long method | Long method2 Magic numbers3 Hard-coded strings4 Code duplication | t | f | t | 0 | 6662 | https://github.com/eclipse/xtext-eclipse/blob/0c7546b6aaf3644a77fc68eef9f3da368cbbeabd/org.eclipse.xtext.ui.tests/src-gen/org/eclipse/xtext/ui/tests/editor/contentassist/parser/antlr/internal/InternalCrossReferenceProposalTestLanguageLexer.java/#L373-L429 | 2 | 3412 | 6662 | minor | ||
| 1679 | YES, I found bad smells. The bad smells are: 1. Long method, 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void log(Operation op, OperationProcessingContext context, String msg, Level logLevel) { String hostId = context.host != null ? context.host.getId() : ""; String path = op.getUri() != null ? op.getUri().getPath() : ""; Filter filter = this.filters.get(context.currentFilterPosition); String filterName = filter != null ? filter.getClass().getSimpleName() : ""; String logMsg = String.format("(host: %s, op %d %s %s) filter %s: %s", hostId, op.getId(), op.getAction(), path, filterName, msg); Level level = logLevel != null ? logLevel : Level.INFO; Utils.log(getClass(), op.getUri().getPath(), level, logMsg); } |
long method | Long method, 2 Duplicated code, 3 Conditional complexity, 4 Long parameter list | t | f | t | 2. Duplicated code, 3. Conditional complexity, 4. Long parameter list | 0 | 11653 | https://github.com/vmware/xenon/blob/b6fb48b745985af2efc59b7ee0e5e7d69a289fbc/xenon-common/src/main/java/com/vmware/xenon/common/OperationProcessingChain.java/#L345-L354 | 2 | 1679 | 11653 | minor | |
| 388 | YES I found bad smells the bad smells are: 1.Long method, 2.Magic numbers, 3.Magic strings, 4.Hardcoded values, 5.Deeply nested code, 6.Feature envy, 7.Inappropriate coupling, 8.Inconsistent naming conventions. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) { final String binaryLabel = binary.getLabel(); final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel + "' settings. Check your '" + binaryLabel + "' configuration and preferences under the corresponding "; final String link = "preference page"; final String suffix = "."; final String text = prefix + link + suffix; final Composite control = new Composite(parent, NONE); control.setLayout(GridLayoutFactory.fillDefaults().create()); final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create(); control.setLayoutData(gridData); final StyleRange style = new StyleRange(); style.underline = true; style.underlineStyle = UNDERLINE_LINK; final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP); styledText.setWordWrap(true); styledText.setJustify(true); styledText.setText(text); final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create(); textGridData.widthHint = TEXT_WIDTH_HINT; textGridData.heightHint = TEXT_HEIGHT_HINT; styledText.setLayoutData(textGridData); styledText.setEditable(false); styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND)); final int[] ranges = { text.indexOf(link), link.length() }; final StyleRange[] styles = { style }; styledText.setStyleRanges(ranges, styles); styledText.addMouseListener(new MouseAdapter() { @Override public void mouseDown(final MouseEvent event) { try { final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y)); final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null; if (null != actualStyle && actualStyle.underline && UNDERLINE_LINK == actualStyle.underlineStyle) { dialog.close(); final PreferenceDialog preferenceDialog = createPreferenceDialogOn( UIUtils.getShell(), BinariesPreferencePage.ID, FILTER_IDS, null); if (null != preferenceDialog) { preferenceDialog.open(); } } } catch (final IllegalArgumentException e) { // We are not over the actual text. } } }); return control; } |
feature envy | Long method, 2Magic numbers, 3Magic strings, 4Hardcoded values, 5Deeply nested code, 6Feature envy, 7Inappropriate coupling, 8Inconsistent naming conventions | t | f | t | .Long method, 2.Magic numbers, 3.Magic strings, 4.Hardcoded values, 5.Deeply nested code, 7.Inappropriate coupling, 8.Inconsistent naming conventions. | 0 | 3945 | https://github.com/eclipse/n4js/blob/f715912fce0352ab574ff878086f77d17a78c908/plugins/org.eclipse.n4js.ui/src/org/eclipse/n4js/ui/binaries/IllegalBinaryStateDialog.java/#L97-L160 | 2 | 388 | 3945 | major | |
| 1459 | { "message": "YES I found bad smells", "bad smells are": [ "Feature Envy", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | feature envy, long method | t | t | t | feature envy | 0 | 11020 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 1 | 1459 | 11020 | minor | |
| 28 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | data class, long method | t | t | t | data class | 0 | 712 | https://github.com/eclipse/elk/blob/9a87764f00d863463b1be6de1920d8aa3c3ade70/plugins/org.eclipse.elk.core.meta.ui/src-gen/org/eclipse/elk/core/meta/ide/contentassist/antlr/internal/InternalMetaDataParser.java/#L22554-L22599 | 1 | 28 | 712 | critical | |
| 493 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Entity public class Customer230 { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String firstName; private String lastName; protected Customer230() {} public Customer230(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format("Customer230[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } } |
data class | data class | t | t | t | 0 | 4960 | https://github.com/spring-projects/spring-data-examples/blob/ccae97890f85a3eaf8f4e05a1a07696e2b1e78a4/jpa/deferred/src/main/java/example/model/Customer230.java/#L8-L27 | 1 | 493 | 4960 | minor | ||
| 2192 | { "output": "YES I found bad smells", "bad smells are": [ "Blob", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Status { public String getAction() { return action; } public Result getResult() { return result; } public String getDetails() { return details; } private String action; private Result result; private String details; public Status(String action, Result result, String details) { this.action = action; this.result = result; this.details = details; } public static enum Result { SUCCESSFUL, FAILED, } @Override public String toString() { return String.format("%s\t%s\t%s", action, result, details); } } |
data class | blob, data class | t | t | t | blob | 0 | 13474 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/azuretools-core/src/com/microsoft/azuretools/authmanage/srvpri/step/Status.java/#L28-L59 | 1 | 2192 | 13474 | major | |
| 2398 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public List getOrderedLogFileIds() { File fileLogDir = new File(logDir); String[] logFileNames = null; List logFileIds = null; if (!fileLogDir.exists()) { LOGGER.log(Level.INFO, "log dir " + logDir + " doesn't exist. returning empty list"); return Collections.emptyList(); } if (!fileLogDir.isDirectory()) { throw new IllegalStateException("log dir " + logDir + " exists but it is not a directory"); } logFileNames = fileLogDir.list((dir, name) -> name.startsWith(logFilePrefix)); if (logFileNames == null) { throw new IllegalStateException("listing of log dir (" + logDir + ") files returned null. " + "Either an IO error occurred or the dir was just deleted by another process/thread"); } if (logFileNames.length == 0) { LOGGER.log(Level.INFO, "the log dir (" + logDir + ") is empty. returning empty list"); return Collections.emptyList(); } logFileIds = new ArrayList<>(); for (String fileName : logFileNames) { logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1))); } logFileIds.sort(Long::compareTo); return logFileIds; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 14376 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java/#L440-L466 | 2 | 2398 | 14376 | minor | ||
| 1817 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Temporary fields 4. Duplicate code 5. Catch-all exception handling 6. Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | Long method2 Feature envy3 Temporary fields4 Duplicate code5 Catch-all exception handling6 Resource cleanup issues (closing sentryClient in finally block instead of using try-with-resources) | t | f | t | 0 | 12088 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 2 | 1817 | 12088 | minor | ||
| 1386 | { "message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static class OnheapDecodedCell implements ExtendedCell { private static final long FIXED_OVERHEAD = ClassSize.align(ClassSize.OBJECT + (3 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_LONG) + (7 * Bytes.SIZEOF_INT) + (Bytes.SIZEOF_SHORT) + (2 * Bytes.SIZEOF_BYTE) + (3 * ClassSize.ARRAY)); private byte[] keyOnlyBuffer; private short rowLength; private int familyOffset; private byte familyLength; private int qualifierOffset; private int qualifierLength; private long timestamp; private byte typeByte; private byte[] valueBuffer; private int valueOffset; private int valueLength; private byte[] tagsBuffer; private int tagsOffset; private int tagsLength; private long seqId; protected OnheapDecodedCell(byte[] keyBuffer, short rowLength, int familyOffset, byte familyLength, int qualOffset, int qualLength, long timeStamp, byte typeByte, byte[] valueBuffer, int valueOffset, int valueLen, long seqId, byte[] tagsBuffer, int tagsOffset, int tagsLength) { this.keyOnlyBuffer = keyBuffer; this.rowLength = rowLength; this.familyOffset = familyOffset; this.familyLength = familyLength; this.qualifierOffset = qualOffset; this.qualifierLength = qualLength; this.timestamp = timeStamp; this.typeByte = typeByte; this.valueBuffer = valueBuffer; this.valueOffset = valueOffset; this.valueLength = valueLen; this.tagsBuffer = tagsBuffer; this.tagsOffset = tagsOffset; this.tagsLength = tagsLength; setSequenceId(seqId); } @Override public byte[] getRowArray() { return keyOnlyBuffer; } @Override public byte[] getFamilyArray() { return keyOnlyBuffer; } @Override public byte[] getQualifierArray() { return keyOnlyBuffer; } @Override public int getRowOffset() { return Bytes.SIZEOF_SHORT; } @Override public short getRowLength() { return rowLength; } @Override public int getFamilyOffset() { return familyOffset; } @Override public byte getFamilyLength() { return familyLength; } @Override public int getQualifierOffset() { return qualifierOffset; } @Override public int getQualifierLength() { return qualifierLength; } @Override public long getTimestamp() { return timestamp; } @Override public byte getTypeByte() { return typeByte; } @Override public long getSequenceId() { return seqId; } @Override public byte[] getValueArray() { return this.valueBuffer; } @Override public int getValueOffset() { return valueOffset; } @Override public int getValueLength() { return valueLength; } @Override public byte[] getTagsArray() { return this.tagsBuffer; } @Override public int getTagsOffset() { return this.tagsOffset; } @Override public int getTagsLength() { return tagsLength; } @Override public String toString() { return KeyValue.keyToString(this.keyOnlyBuffer, 0, KeyValueUtil.keyLength(this)) + "/vlen=" + getValueLength() + "/seqid=" + seqId; } @Override public void setSequenceId(long seqId) { this.seqId = seqId; } @Override public long heapSize() { return FIXED_OVERHEAD + rowLength + familyLength + qualifierLength + valueLength + tagsLength; } @Override public int write(OutputStream out, boolean withTags) throws IOException { int lenToWrite = getSerializedSize(withTags); ByteBufferUtils.putInt(out, keyOnlyBuffer.length); ByteBufferUtils.putInt(out, valueLength); // Write key out.write(keyOnlyBuffer); // Write value out.write(this.valueBuffer, this.valueOffset, this.valueLength); if (withTags && this.tagsLength > 0) { // 2 bytes tags length followed by tags bytes // tags length is serialized with 2 bytes only(short way) even if the type is int. // As this is non -ve numbers, we save the sign bit. See HBASE-11437 out.write((byte) (0xff & (this.tagsLength >> 8))); out.write((byte) (0xff & this.tagsLength)); out.write(this.tagsBuffer, this.tagsOffset, this.tagsLength); } return lenToWrite; } @Override public int getSerializedSize(boolean withTags) { return KeyValueUtil.length(rowLength, familyLength, qualifierLength, valueLength, tagsLength, withTags); } @Override public void write(ByteBuffer buf, int offset) { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(long ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public void setTimestamp(byte[] ts) throws IOException { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } @Override public ExtendedCell deepClone() { // This is not used in actual flow. Throwing UnsupportedOperationException throw new UnsupportedOperationException(); } } |
data class | data class, long method | t | t | t | long method | 0 | 10834 | https://github.com/apache/hbase/blob/44f8abd5c65c59e9d09f6ad14b3c825f145d8e4f/hbase-common/src/main/java/org/apache/hadoop/hbase/io/encoding/BufferedDataBlockEncoder.java/#L282-L478 | 1 | 1386 | 10834 | critical | |
| 4734 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob", "Feature Envy"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DebugInfoDecoder { /** encoded debug info */ private final byte[] encoded; /** positions decoded */ private final ArrayList positions; /** locals decoded */ private final ArrayList locals; /** size of code block in code units */ private final int codesize; /** indexed by register, the last local variable live in a reg */ private final LocalEntry[] lastEntryForReg; /** method descriptor of method this debug info is for */ private final Prototype desc; /** true if method is static */ private final boolean isStatic; /** dex file this debug info will be stored in */ private final DexFile file; /** * register size, in register units, of the register space * used by this method */ private final int regSize; /** current decoding state: line number */ private int line = 1; /** current decoding state: bytecode address */ private int address = 0; /** string index of the string "this" */ private final int thisStringIdx; /** * Constructs an instance. * * @param encoded encoded debug info * @param codesize size of code block in code units * @param regSize register size, in register units, of the register space * used by this method * @param isStatic true if method is static * @param ref method descriptor of method this debug info is for * @param file dex file this debug info will be stored in */ DebugInfoDecoder(byte[] encoded, int codesize, int regSize, boolean isStatic, CstMethodRef ref, DexFile file) { if (encoded == null) { throw new NullPointerException("encoded == null"); } this.encoded = encoded; this.isStatic = isStatic; this.desc = ref.getPrototype(); this.file = file; this.regSize = regSize; positions = new ArrayList(); locals = new ArrayList(); this.codesize = codesize; lastEntryForReg = new LocalEntry[regSize]; int idx = -1; try { idx = file.getStringIds().indexOf(new CstString("this")); } catch (IllegalArgumentException ex) { /* * Silently tolerate not finding "this". It just means that * no method has local variable info that looks like * a standard instance method. */ } thisStringIdx = idx; } /** * An entry in the resulting postions table */ static private class PositionEntry { /** bytecode address */ public int address; /** line number */ public int line; public PositionEntry(int address, int line) { this.address = address; this.line = line; } } /** * An entry in the resulting locals table */ static private class LocalEntry { /** address of event */ public int address; /** {@code true} iff it's a local start */ public boolean isStart; /** register number */ public int reg; /** index of name in strings table */ public int nameIndex; /** index of type in types table */ public int typeIndex; /** index of type signature in strings table */ public int signatureIndex; public LocalEntry(int address, boolean isStart, int reg, int nameIndex, int typeIndex, int signatureIndex) { this.address = address; this.isStart = isStart; this.reg = reg; this.nameIndex = nameIndex; this.typeIndex = typeIndex; this.signatureIndex = signatureIndex; } public String toString() { return String.format("[%x %s v%d %04x %04x %04x]", address, isStart ? "start" : "end", reg, nameIndex, typeIndex, signatureIndex); } } /** * Gets the decoded positions list. * Valid after calling {@code decode}. * * @return positions list in ascending address order. */ public List getPositionList() { return positions; } /** * Gets the decoded locals list, in ascending start-address order. * Valid after calling {@code decode}. * * @return locals list in ascending address order. */ public List getLocals() { return locals; } /** * Decodes the debug info sequence. */ public void decode() { try { decode0(); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "...while decoding debug info"); } } /** * Reads a string index. String indicies are offset by 1, and a 0 value * in the stream (-1 as returned by this method) means "null" * * @return index into file's string ids table, -1 means null * @throws IOException */ private int readStringIndex(ByteInput bs) throws IOException { int offsetIndex = Leb128.readUnsignedLeb128(bs); return offsetIndex - 1; } /** * Gets the register that begins the method's parameter range (including * the 'this' parameter for non-static methods). The range continues until * {@code regSize} * * @return register as noted above. */ private int getParamBase() { return regSize - desc.getParameterTypes().getWordCount() - (isStatic? 0 : 1); } private void decode0() throws IOException { ByteInput bs = new ByteArrayByteInput(encoded); line = Leb128.readUnsignedLeb128(bs); int szParams = Leb128.readUnsignedLeb128(bs); StdTypeList params = desc.getParameterTypes(); int curReg = getParamBase(); if (szParams != params.size()) { throw new RuntimeException( "Mismatch between parameters_size and prototype"); } if (!isStatic) { // Start off with implicit 'this' entry LocalEntry thisEntry = new LocalEntry(0, true, curReg, thisStringIdx, 0, 0); locals.add(thisEntry); lastEntryForReg[curReg] = thisEntry; curReg++; } for (int i = 0; i < szParams; i++) { Type paramType = params.getType(i); LocalEntry le; int nameIdx = readStringIndex(bs); if (nameIdx == -1) { /* * Unnamed parameter; often but not always filled in by an * extended start op after the prologue */ le = new LocalEntry(0, true, curReg, -1, 0, 0); } else { // TODO: Final 0 should be idx of paramType.getDescriptor(). le = new LocalEntry(0, true, curReg, nameIdx, 0, 0); } locals.add(le); lastEntryForReg[curReg] = le; curReg += paramType.getCategory(); } for (;;) { int opcode = bs.readByte() & 0xff; switch (opcode) { case DBG_START_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, 0); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_START_LOCAL_EXTENDED: { int reg = Leb128.readUnsignedLeb128(bs); int nameIdx = readStringIndex(bs); int typeIdx = readStringIndex(bs); int sigIdx = readStringIndex(bs); LocalEntry le = new LocalEntry( address, true, reg, nameIdx, typeIdx, sigIdx); locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_RESTART_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (prevle.isStart) { throw new RuntimeException("nonsensical " + "RESTART_LOCAL on live register v" + reg); } le = new LocalEntry(address, true, reg, prevle.nameIndex, prevle.typeIndex, 0); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered RESTART_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_LOCAL: { int reg = Leb128.readUnsignedLeb128(bs); LocalEntry prevle; LocalEntry le; try { prevle = lastEntryForReg[reg]; if (!prevle.isStart) { throw new RuntimeException("nonsensical " + "END_LOCAL on dead register v" + reg); } le = new LocalEntry(address, false, reg, prevle.nameIndex, prevle.typeIndex, prevle.signatureIndex); } catch (NullPointerException ex) { throw new RuntimeException( "Encountered END_LOCAL on new v" + reg); } locals.add(le); lastEntryForReg[reg] = le; } break; case DBG_END_SEQUENCE: // all done return; case DBG_ADVANCE_PC: address += Leb128.readUnsignedLeb128(bs); break; case DBG_ADVANCE_LINE: line += Leb128.readSignedLeb128(bs); break; case DBG_SET_PROLOGUE_END: //TODO do something with this. break; case DBG_SET_EPILOGUE_BEGIN: //TODO do something with this. break; case DBG_SET_FILE: //TODO do something with this. break; default: if (opcode < DBG_FIRST_SPECIAL) { throw new RuntimeException( "Invalid extended opcode encountered " + opcode); } int adjopcode = opcode - DBG_FIRST_SPECIAL; address += adjopcode / DBG_LINE_RANGE; line += DBG_LINE_BASE + (adjopcode % DBG_LINE_RANGE); positions.add(new PositionEntry(address, line)); break; } } } /** * Validates an encoded debug info stream against data used to encode it, * throwing an exception if they do not match. Used to validate the * encoder. * * @param info encoded debug info * @param file {@code non-null;} file to refer to during decoding * @param ref {@code non-null;} method whose info is being decoded * @param code {@code non-null;} original code object that was encoded * @param isStatic whether the method is static */ public static void validateEncode(byte[] info, DexFile file, CstMethodRef ref, DalvCode code, boolean isStatic) { PositionList pl = code.getPositions(); LocalList ll = code.getLocals(); DalvInsnList insns = code.getInsns(); int codeSize = insns.codeSize(); int countRegisters = insns.getRegistersSize(); try { validateEncode0(info, codeSize, countRegisters, isStatic, ref, file, pl, ll); } catch (RuntimeException ex) { System.err.println("instructions:"); insns.debugPrint(System.err, " ", true); System.err.println("local list:"); ll.debugPrint(System.err, " "); throw ExceptionWithContext.withContext(ex, "while processing " + ref.toHuman()); } } private static void validateEncode0(byte[] info, int codeSize, int countRegisters, boolean isStatic, CstMethodRef ref, DexFile file, PositionList pl, LocalList ll) { DebugInfoDecoder decoder = new DebugInfoDecoder(info, codeSize, countRegisters, isStatic, ref, file); decoder.decode(); /* * Go through the decoded position entries, matching up * with original entries. */ List decodedEntries = decoder.getPositionList(); if (decodedEntries.size() != pl.size()) { throw new RuntimeException( "Decoded positions table not same size was " + decodedEntries.size() + " expected " + pl.size()); } for (PositionEntry entry : decodedEntries) { boolean found = false; for (int i = pl.size() - 1; i >= 0; i--) { PositionList.Entry ple = pl.get(i); if (entry.line == ple.getPosition().getLine() && entry.address == ple.getAddress()) { found = true; break; } } if (!found) { throw new RuntimeException ("Could not match position entry: " + entry.address + ", " + entry.line); } } /* * Go through the original local list, in order, matching up * with decoded entries. */ List decodedLocals = decoder.getLocals(); int thisStringIdx = decoder.thisStringIdx; int decodedSz = decodedLocals.size(); int paramBase = decoder.getParamBase(); /* * Preflight to fill in any parameters that were skipped in * the prologue (including an implied "this") but then * identified by full signature. */ for (int i = 0; i < decodedSz; i++) { LocalEntry entry = decodedLocals.get(i); int idx = entry.nameIndex; if ((idx < 0) || (idx == thisStringIdx)) { for (int j = i + 1; j < decodedSz; j++) { LocalEntry e2 = decodedLocals.get(j); if (e2.address != 0) { break; } if ((entry.reg == e2.reg) && e2.isStart) { decodedLocals.set(i, e2); decodedLocals.remove(j); decodedSz--; break; } } } } int origSz = ll.size(); int decodeAt = 0; boolean problem = false; for (int i = 0; i < origSz; i++) { LocalList.Entry origEntry = ll.get(i); if (origEntry.getDisposition() == LocalList.Disposition.END_REPLACED) { /* * The encoded list doesn't represent replacements, so * ignore them for the sake of comparison. */ continue; } LocalEntry decodedEntry; do { decodedEntry = decodedLocals.get(decodeAt); if (decodedEntry.nameIndex >= 0) { break; } /* * A negative name index means this is an anonymous * parameter, and we shouldn't expect to see it in the * original list. So, skip it. */ decodeAt++; } while (decodeAt < decodedSz); int decodedAddress = decodedEntry.address; if (decodedEntry.reg != origEntry.getRegister()) { System.err.println("local register mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } if (decodedEntry.isStart != origEntry.isStart()) { System.err.println("local start/end mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } /* * The secondary check here accounts for the fact that a * parameter might not be marked as starting at 0 in the * original list. */ if ((decodedAddress != origEntry.getAddress()) && !((decodedAddress == 0) && (decodedEntry.reg >= paramBase))) { System.err.println("local address mismatch at orig " + i + " / decoded " + decodeAt); problem = true; break; } decodeAt++; } if (problem) { System.err.println("decoded locals:"); for (LocalEntry e : decodedLocals) { System.err.println(" " + e); } throw new RuntimeException("local table problem"); } } } |
blob | blob, feature envy | t | t | t | feature envy | 0 | 12715 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/third-party/java/dx/src/com/android/dx/dex/file/DebugInfoDecoder.java/#L54-L596 | 1 | 4734 | 12715 | critical | |
| 2317 | {"response": "YES I found bad smells", "bad smells are": ["1. Long Method", "2. Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class PartitionCollapsingSchemas implements Serializable { private static String DATED_INTERMEDIATE_VALUE_SCHEMA_NAME = "DatedMapValue"; private static String KEY_SCHEMA = "key.schema"; private static String INTERMEDIATE_VALUE_SCHEMA = "intermediate.value.schema"; private static String OUTPUT_VALUE_SCHEMA = "output.value.schema"; private final String _outputSchemaName; private final String _outputSchemaNamespace; private transient Schema _keySchema; private transient Schema _intermediateValueSchema; private transient Schema _outputValueSchema; // generated schemas private transient Schema _mapOutputSchema; private transient Schema _dateIntermediateValueSchema; private transient Schema _mapOutputValueSchema; private transient Schema _reduceOutputSchema; private transient Map _mapInputSchemas; //schemas are stored here so the object can be serialized private Map conf; private Map _inputSchemas; public PartitionCollapsingSchemas(TaskSchemas schemas, Map inputSchemas, String outputSchemaName, String outputSchemaNamespace) { if (schemas == null) { throw new NullArgumentException("schemas"); } if (inputSchemas == null) { throw new NullArgumentException("inputSchema"); } if (outputSchemaName == null) { throw new NullArgumentException("outputSchemaName"); } if (outputSchemaName == outputSchemaNamespace) { throw new NullArgumentException("outputSchemaNamespace"); } _outputSchemaName = outputSchemaName; _outputSchemaNamespace = outputSchemaNamespace; conf = new HashMap(); conf.put(KEY_SCHEMA, schemas.getKeySchema().toString()); conf.put(INTERMEDIATE_VALUE_SCHEMA, schemas.getIntermediateValueSchema().toString()); conf.put(OUTPUT_VALUE_SCHEMA, schemas.getOutputValueSchema().toString()); _inputSchemas = new HashMap(); for (Entry schema : inputSchemas.entrySet()) { _inputSchemas.put(schema.getKey(), schema.getValue().toString()); } } public Map getMapInputSchemas() { if (_mapInputSchemas == null) { _mapInputSchemas = new HashMap(); for (Entry schemaPair : _inputSchemas.entrySet()) { Schema schema = new Schema.Parser().parse(schemaPair.getValue()); List mapInputSchemas = new ArrayList(); if (schema.getType() == Type.UNION) { mapInputSchemas.addAll(schema.getTypes()); } else { mapInputSchemas.add(schema); } // feedback from output (optional) mapInputSchemas.add(getReduceOutputSchema()); _mapInputSchemas.put(schemaPair.getKey(), Schema.createUnion(mapInputSchemas)); } } return Collections.unmodifiableMap(_mapInputSchemas); } public Schema getMapOutputSchema() { if (_mapOutputSchema == null) { _mapOutputSchema = Pair.getPairSchema(getMapOutputKeySchema(), getMapOutputValueSchema()); } return _mapOutputSchema; } public Schema getKeySchema() { if (_keySchema == null) { _keySchema = new Schema.Parser().parse(conf.get(KEY_SCHEMA)); } return _keySchema; } public Schema getMapOutputKeySchema() { return getKeySchema(); } public Schema getReduceOutputSchema() { if (_reduceOutputSchema == null) { _reduceOutputSchema = Schema.createRecord(_outputSchemaName, null, _outputSchemaNamespace, false); List fields = Arrays.asList(new Field("key",getKeySchema(), null, null), new Field("value", getOutputValueSchema(), null, null)); _reduceOutputSchema.setFields(fields); } return _reduceOutputSchema; } public Schema getDatedIntermediateValueSchema() { if (_dateIntermediateValueSchema == null) { _dateIntermediateValueSchema = Schema.createRecord(DATED_INTERMEDIATE_VALUE_SCHEMA_NAME, null, _outputSchemaNamespace, false); List intermediateValueFields = Arrays.asList(new Field("value", getIntermediateValueSchema(), null, null), new Field("time", Schema.create(Type.LONG), null, null)); _dateIntermediateValueSchema.setFields(intermediateValueFields); } return _dateIntermediateValueSchema; } public Schema getOutputValueSchema() { if (_outputValueSchema == null) { _outputValueSchema = new Schema.Parser().parse(conf.get(OUTPUT_VALUE_SCHEMA)); } return _outputValueSchema; } public Schema getIntermediateValueSchema() { if (_intermediateValueSchema == null) { _intermediateValueSchema = new Schema.Parser().parse(conf.get(INTERMEDIATE_VALUE_SCHEMA)); } return _intermediateValueSchema; } public Schema getMapOutputValueSchema() { if (_mapOutputValueSchema == null) { List unionSchemas = new ArrayList(); unionSchemas.add(getIntermediateValueSchema()); // intermediate values tagged with the date unionSchemas.add(getDatedIntermediateValueSchema()); // feedback from output of second pass if (!unionSchemas.contains(getOutputValueSchema())) { unionSchemas.add(getOutputValueSchema()); } _mapOutputValueSchema = Schema.createUnion(unionSchemas); } return _mapOutputValueSchema; } } |
data class | 1. long method, 2. data class | t | t | t | 1. long method | 0 | 14122 | https://github.com/apache/datafu/blob/3e52d11f75956ac3e6d2384816affeba565ab61d/datafu-hourglass/src/main/java/datafu/hourglass/schemas/PartitionCollapsingSchemas.java/#L41-L218 | 1 | 2317 | 14122 | major | |
| 599 | { "response": "YES I found bad smells", "bad smells are": ["Data Class"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DeploymentPlannersResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description = "Deployment Planner name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
data class | data class | t | t | t | 0 | 5988 | https://github.com/apache/cloudstack/blob/8d3feb100aab4a45b31a789f444038b892161eec/api/src/main/java/org/apache/cloudstack/api/response/DeploymentPlannersResponse.java/#L26-L38 | 1 | 599 | 5988 | minor | ||
| 1830 | {"response": "YES, I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public double correlation(final double[] xArray, final double[] yArray) throws DimensionMismatchException { if (xArray.length != yArray.length) { throw new DimensionMismatchException(xArray.length, yArray.length); } final int n = xArray.length; final long numPairs = sum(n - 1); @SuppressWarnings("unchecked") Pair[] pairs = new Pair[n]; for (int i = 0; i < n; i++) { pairs[i] = new Pair<>(xArray[i], yArray[i]); } Arrays.sort(pairs, new Comparator>() { /** {@inheritDoc} */ @Override public int compare(Pair pair1, Pair pair2) { int compareFirst = pair1.getFirst().compareTo(pair2.getFirst()); return compareFirst != 0 ? compareFirst : pair1.getSecond().compareTo(pair2.getSecond()); } }); long tiedXPairs = 0; long tiedXYPairs = 0; long consecutiveXTies = 1; long consecutiveXYTies = 1; Pair prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getFirst().equals(prev.getFirst())) { consecutiveXTies++; if (curr.getSecond().equals(prev.getSecond())) { consecutiveXYTies++; } else { tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } } else { tiedXPairs += sum(consecutiveXTies - 1); consecutiveXTies = 1; tiedXYPairs += sum(consecutiveXYTies - 1); consecutiveXYTies = 1; } prev = curr; } tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); long swaps = 0; @SuppressWarnings("unchecked") Pair[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) { for (int offset = 0; offset < n; offset += 2 * segmentSize) { int i = offset; final int iEnd = FastMath.min(i + segmentSize, n); int j = iEnd; final int jEnd = FastMath.min(j + segmentSize, n); int copyLocation = offset; while (i < iEnd || j < jEnd) { if (i < iEnd) { if (j < jEnd) { if (pairs[i].getSecond().compareTo(pairs[j].getSecond()) <= 0) { pairsDestination[copyLocation] = pairs[i]; i++; } else { pairsDestination[copyLocation] = pairs[j]; j++; swaps += iEnd - i; } } else { pairsDestination[copyLocation] = pairs[i]; i++; } } else { pairsDestination[copyLocation] = pairs[j]; j++; } copyLocation++; } } final Pair[] pairsTemp = pairs; pairs = pairsDestination; pairsDestination = pairsTemp; } long tiedYPairs = 0; long consecutiveYTies = 1; prev = pairs[0]; for (int i = 1; i < n; i++) { final Pair curr = pairs[i]; if (curr.getSecond().equals(prev.getSecond())) { consecutiveYTies++; } else { tiedYPairs += sum(consecutiveYTies - 1); consecutiveYTies = 1; } prev = curr; } tiedYPairs += sum(consecutiveYTies - 1); final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } |
long method | long method | t | t | t | 0 | 12121 | https://github.com/apache/commons-math/blob/f3719d89ab6a928e8618bbe6a7da8214d9d6eb07/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java/#L154-L261 | 1 | 1830 | 12121 | critical | ||
| 1038 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public CallableStatement prepareCall(String sql) throws SQLException { checkState(); PreparedStatementHolder stmtHolder = null; PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.Precall_1); boolean poolPreparedStatements = holder.isPoolPreparedStatements(); if (poolPreparedStatements) { stmtHolder = holder.getStatementPool().get(key); } if (stmtHolder == null) { try { stmtHolder = new PreparedStatementHolder(key, conn.prepareCall(sql)); holder.getDataSource().incrementPreparedStatementCount(); } catch (SQLException ex) { handleException(ex, sql); } } initStatement(stmtHolder); DruidPooledCallableStatement rtnVal = new DruidPooledCallableStatement(this, stmtHolder); holder.addTrace(rtnVal); return rtnVal; } |
long method | long method | t | t | t | 0 | 9410 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledConnection.java/#L534-L563 | 1 | 1038 | 9410 | minor | ||
| 2461 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "cache-policy-conf-other") public class CachePolicyConfOther { @XmlMixed @XmlAnyElement protected List content; /** * Gets the value of the content property. * * * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. * * * For example, to add a new item, do as follows: * * getContent().add(newItem); * * * * * Objects of the following type(s) are allowed in the list * {@link Element } * {@link String } */ public List getContent() { if (content == null) { content = new ArrayList(); } return this.content; } } |
data class | data class, long method | t | t | t | long method | 0 | 14541 | https://github.com/apache/tomee/blob/d21933b313aff812fe5188b57bf572a9ad649148/container/openejb-jee/src/main/java/org/apache/openejb/jee/jba/CachePolicyConfOther.java/#L32-L71 | 1 | 2461 | 14541 | major | |
| 2548 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops/cyclomatic complexity 4. Inconsistent indentation 5. Complex conditional statements 6. Magic numbers/unnamed variables 7. Unused/unnecessary variables 8. Lack of comments/documentation 9. Use of null values 10. Large class/object 11. Inefficient use of data structures 12. Code duplication 13. Unclear naming conventions for variables/methods 14. Multiple return statements within a method. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: boolean increaseConnectionWindow(int amount) { List> candidates = null; controllerLock.lock(); try { int size = connectionWindowSize; size += amount; if (size < 0) return false; connectionWindowSize = size; if (debug.on()) debug.log("Connection window size is now %d (amount added %d)", size, amount); // Notify waiting streams, until the new increased window size is // effectively exhausted. Iterator,Integer>>> iter = pending.entrySet().iterator(); while (iter.hasNext() && size > 0) { Map.Entry,Integer>> item = iter.next(); Integer streamSize = streams.get(item.getKey()); if (streamSize == null) { iter.remove(); } else { Map.Entry,Integer> e = item.getValue(); int requestedAmount = e.getValue(); // only wakes up the pending streams for which there is // at least 1 byte of space in both windows int minAmount = 1; if (size >= minAmount && streamSize >= minAmount) { size -= Math.min(streamSize, requestedAmount); iter.remove(); if (candidates == null) candidates = new ArrayList<>(); candidates.add(e.getKey()); } } } } finally { controllerLock.unlock(); } if (candidates != null) { candidates.forEach(Stream::signalWindowUpdate); } return true; } |
long method | Long method2 Feature envy3 Nested loops/cyclomatic complexity4 Inconsistent indentation5 Complex conditional statements6 Magic numbers/unnamed variables7 Unused/unnecessary variables 8 Lack of comments/documentation 9 Use of null values | t | f | t | 0 | 14793 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.net.http/share/classes/jdk/internal/net/http/WindowController.java/#L181-L226 | 2 | 2548 | 14793 | minor | ||
| 5324 | {"output": "YES I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | 1. long method | t | t | t | 0 | 14946 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 5324 | 14946 | major | ||
| 423 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected JvmField createField(Field field) { JvmField result; int modifiers = field.getModifiers(); if (!field.isEnumConstant()) { result = TypesFactory.eINSTANCE.createJvmField(); } else result = TypesFactory.eINSTANCE.createJvmEnumerationLiteral(); String fieldName = field.getName(); result.internalSetIdentifier(field.getDeclaringClass().getName() + "." + fieldName); result.setSimpleName(fieldName); result.setFinal(Modifier.isFinal(modifiers)); result.setStatic(Modifier.isStatic(modifiers)); result.setTransient(Modifier.isTransient(modifiers)); result.setVolatile(Modifier.isVolatile(modifiers)); setVisibility(result, modifiers); Type fieldType = null; try { fieldType = field.getGenericType(); } catch (GenericSignatureFormatError error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } catch (MalformedParameterizedTypeException error) { logSignatureFormatError(field.getDeclaringClass()); fieldType = field.getType(); } result.setType(createTypeReference(fieldType)); createAnnotationValues(field, result); return result; } |
long method | Long method 2 Feature envy | t | f | t | 0 | 4247 | https://github.com/eclipse/xtext-extras/blob/5634c291880cd46fe2f8e9a47e48ef88b85e8bda/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/reflect/ReflectionTypeFactory.java/#L618-L646 | 2 | 423 | 4247 | major | ||
| 1810 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public static String shortenDbName(String dbName, int desiredLength) { StringBuilder dbBuf = new StringBuilder(dbName); if (dbBuf.length() > desiredLength) { // remove one vowel at a time, starting at beginning for (int i = dbBuf.length() - 1; i > 0; i--) { // don't remove vowels that are at the beginning of the string (taken care of by the i > 0) or right after an underscore if (dbBuf.charAt(i - 1) == '_') { continue; } char curChar = dbBuf.charAt(i); if (vowelBag.indexOf(curChar) > 0) { dbBuf.deleteCharAt(i); } } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { boolean removedChars = false; int usIndex = dbBuf.lastIndexOf("_"); while (usIndex > 0 && dbBuf.length() > desiredLength) { // if this is the first word in the group, don't pull letters off unless it is 4 letters or more int prevUsIndex = dbBuf.lastIndexOf("_", usIndex - 1); if (prevUsIndex < 0 && usIndex < 4) { break; } // don't remove characters to reduce the size two less than three characters between underscores if (prevUsIndex >= 0 && (usIndex - prevUsIndex) <= 4) { usIndex = prevUsIndex; continue; } // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(usIndex - 2); removedChars = true; if (usIndex > 2) { usIndex = dbBuf.lastIndexOf("_", usIndex - 2); } else { break; } } // now delete the char at the end of the string if necessary if (dbBuf.length() > desiredLength) { int removeIndex = dbBuf.length() - 1; int prevRemoveIndex = dbBuf.lastIndexOf("_", removeIndex - 1); // don't remove characters to reduce the size two less than two characters between underscores if (prevRemoveIndex < 0 || (removeIndex - prevRemoveIndex) >= 3) { // delete the second to last character instead of the last, better chance of being unique dbBuf.deleteCharAt(removeIndex - 1); removedChars = true; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); removedChars = true; } // if we didn't remove anything break out to avoid an infinite loop if (!removedChars) { break; } } // remove all double underscores while (dbBuf.indexOf("__") > 0) { dbBuf.deleteCharAt(dbBuf.indexOf("__")); } while (dbBuf.length() > desiredLength) { // still not short enough, get more aggressive // don't remove the first segment, just remove the second over and over until we are short enough int firstUs = dbBuf.indexOf("_"); if (firstUs > 0) { int nextUs = dbBuf.indexOf("_", firstUs + 1); if (nextUs > 0) { //Debug.logInfo("couldn't shorten enough normally, removing second segment from " + dbBuf, module); dbBuf.delete(firstUs, nextUs); } } } //Debug.logInfo("Shortened " + dbName + " to " + dbBuf.toString(), module); return dbBuf.toString(); } |
long method | Long Method | t | f | t | 0 | 12056 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/entity/src/main/java/org/apache/ofbiz/entity/model/ModelUtil.java/#L155-L248 | 1 | 1810 | 12056 | major | ||
| 1800 | { "output": "YES I found bad smells", "bad smells are": ["Long Method"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: Type asTuple() { final Type result; if (types.size() == 0) { result = unit.getEmptyType(); } else { final Type sequentialType; if (variadic) { Part part = new Part("Sequence", Collections.singletonList(getLast())); sequentialType = loadType("ceylon.language", atLeastOne ? "ceylon.language.Sequence" : "ceylon.language.Sequential", part, null); } else { sequentialType = unit.getEmptyType(); } if (variadic && types.size() == 1) { result = sequentialType; } else { Part part = new Part(); // if we're variadic we put the element type there because we skip it below // if we're not variadic we are not going to skip it so let's not union it with itself Type union = variadic ? getLast() : null; Type tupleType = sequentialType; // A,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // A=,B= // union = null // tupleType = [] // t = B // union = B // tupleType = [B] // tupleType = [B]|[] // t = A // union = A|B // tupleType = [A,[B]|[]] // tupleType = [A,[B]|[]]|[] // A=,B* // union = B // tupleType = [B*] // t = A // union = A|B // tupleType = [A,[B*]] // tupleType = [A,[B*]]|[] int makeDefaulted = defaulted; for (int ii = types.size()-(variadic? 2 : 1); ii >= 0; ii--) { Type t = types.get(ii); // FIXME: subtyping in the type parser may cause issues if(union != null) // any second element (variadic or not) union = ModelUtil.unionType(union, t, unit); else union = t; // any first element part.parameters = Arrays.asList(union, t, tupleType); part.name = "Tuple"; tupleType = loadType("ceylon.language", "ceylon.language.Tuple", part, null); if(makeDefaulted > 0){ makeDefaulted--; tupleType = union(Arrays.asList(unit.getEmptyType(), tupleType), unit); } } result = tupleType; } } return result; } |
long method | Long Method | t | f | t | 0 | 12011 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/model/src/org/eclipse/ceylon/model/loader/TypeParser.java/#L431-L505 | 1 | 1800 | 12011 | minor | ||
| 2432 | YES I found bad smells the bad smells are: 1. Data class 2. Long method 3. Setters and getters (they are not necessary in this case) 4. Lack of encapsulation (id and description are public) 5. Primitive obsession (using long and string instead of more specific types) 6. Tight coupling (the class is tied to the @XmlRootElement annotation and cannot easily be replaced) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @XmlRootElement(name = "Product") public class Product { private long id; private String description; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } } |
data class | Data class2 Long method3 Setters and getters (they are not necessary in this case)4 Lack of encapsulation (id and description are public)5 Primitive obsession (using long and string instead of more specific types)6 Tight coupling (the class is tied to the @XmlRootElement annotation and cannot easily be replaced) | t | f | t | 0 | 14460 | https://github.com/apache/cxf/blob/6bf89e9c8804c8845ec4d38583dd33eea8256439/distribution/src/main/release/samples/jax_rs/spring_security/src/main/java/demo/jaxrs/service/Product.java/#L23-L43 | 2 | 2432 | 14460 | major | ||
| 461 | { "response": "YES, I found bad smells", "detected_bad_smells": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BytesRef next() { if (input.position() < end) { try { int code = input.readVInt(); boolean newField = (code & 1) != 0; if (newField) { field = input.readString(); } int prefix = code >>> 1; int suffix = input.readVInt(); readTermBytes(prefix, suffix); return bytes; } catch (IOException e) { throw new RuntimeException(e); } } else { field = null; return null; } } |
long method | long method | t | t | t | 0 | 4463 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java/#L123-L143 | 1 | 461 | 4463 | minor | ||
| 1055 | { "output": "YES I found bad smells", "bad smells are": [ "Long Method", "Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class XmiWriterCasConsumer extends CasConsumer_ImplBase { /** * Name of configuration parameter that must be set to the path of a directory into which the * output files will be written. */ public static final String PARAM_OUTPUTDIR = "OutputDirectory"; private File mOutputDir; private int mDocNum; public void initialize() throws ResourceInitializationException { mDocNum = 0; mOutputDir = new File((String) getConfigParameterValue(PARAM_OUTPUTDIR)); if (!mOutputDir.exists()) { mOutputDir.mkdirs(); } } /** * Processes the CAS which was populated by the TextAnalysisEngines. * In this case, the CAS is converted to XMI and written into the output file . * * @param aCAS * a CAS which has been populated by the TAEs * * @throws ResourceProcessException * if there is an error in processing the Resource * * @see org.apache.uima.collection.base_cpm.CasObjectProcessor#processCas(org.apache.uima.cas.CAS) */ public void processCas(CAS aCAS) throws ResourceProcessException { String modelFileName = null; JCas jcas; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } // retrieve the filename of the input file from the CAS FSIterator it = jcas.getAnnotationIndex(SourceDocumentInformation.type).iterator(); File outFile = null; if (it.hasNext()) { SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next(); File inFile; try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += ".xmi"; outFile = new File(mOutputDir, outFileName); modelFileName = mOutputDir.getAbsolutePath() + "/" + inFile.getName() + ".ecore"; } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xmi"); } // serialize XCAS and write to output file try { writeXmi(jcas.getCas(), outFile, modelFileName); } catch (IOException e) { throw new ResourceProcessException(e); } catch (SAXException e) { throw new ResourceProcessException(e); } } /** * Serialize a CAS to a file in XMI format * * @param aCas * CAS to serialize * @param name * output file * @throws SAXException - * @throws Exception - * * @throws ResourceProcessException - */ private void writeXmi(CAS aCas, File name, String modelFileName) throws IOException, SAXException { FileOutputStream out = null; try { // write XMI out = new FileOutputStream(name); XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(out, false); ser.serialize(aCas, xmlSer.getContentHandler()); } finally { if (out != null) { out.close(); } } } } |
blob | long method, blob | t | t | t | long method | 0 | 9506 | https://github.com/apache/uima-uimaj/blob/e79c33b5a3e4c25afb407e68e98df1829a68e5a7/uimaj-examples/src/main/java/org/apache/uima/examples/xmi/XmiWriterCasConsumer.java/#L48-L148 | 1 | 1055 | 9506 | minor | |
| 199 | { "output": "YES I found bad smells", "the bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private boolean r_prelude() { int among_var; int v_1; int v_2; int v_3; int v_4; int v_5; // (, line 34 // test, line 35 v_1 = cursor; // repeat, line 35 replab0: while(true) { v_2 = cursor; lab1: do { // (, line 35 // [, line 36 bra = cursor; // substring, line 36 among_var = find_among(a_0, 7); if (among_var == 0) { break lab1; } // ], line 36 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 37 // <-, line 37 slice_from("\u00E0"); break; case 2: // (, line 38 // <-, line 38 slice_from("\u00E8"); break; case 3: // (, line 39 // <-, line 39 slice_from("\u00EC"); break; case 4: // (, line 40 // <-, line 40 slice_from("\u00F2"); break; case 5: // (, line 41 // <-, line 41 slice_from("\u00F9"); break; case 6: // (, line 42 // <-, line 42 slice_from("qU"); break; case 7: // (, line 43 // next, line 43 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_2; break replab0; } cursor = v_1; // repeat, line 46 replab2: while(true) { v_3 = cursor; lab3: do { // goto, line 46 golab4: while(true) { v_4 = cursor; lab5: do { // (, line 46 if (!(in_grouping(g_v, 97, 249))) { break lab5; } // [, line 47 bra = cursor; // or, line 47 lab6: do { v_5 = cursor; lab7: do { // (, line 47 // literal, line 47 if (!(eq_s(1, "u"))) { break lab7; } // ], line 47 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab7; } // <-, line 47 slice_from("U"); break lab6; } while (false); cursor = v_5; // (, line 48 // literal, line 48 if (!(eq_s(1, "i"))) { break lab5; } // ], line 48 ket = cursor; if (!(in_grouping(g_v, 97, 249))) { break lab5; } // <-, line 48 slice_from("I"); } while (false); cursor = v_4; break golab4; } while (false); cursor = v_4; if (cursor >= limit) { break lab3; } cursor++; } continue replab2; } while (false); cursor = v_3; break replab2; } return true; } |
long method | long method | t | t | t | 0 | 2241 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/lucene/analysis/common/src/java/org/tartarus/snowball/ext/ItalianStemmer.java/#L257-L401 | 1 | 199 | 2241 | critical | ||
| 1763 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the for loop) 4. Confusing logic/naming (headerValue vs hdr) 5. Magic numbers (CONFIG_PREFIX_OPTIONAL + ".") 6. Nested loops 7. Use of isEmpty() instead of checking for size() == 0 8. Code comments indicating potential issues or bad practices 9. Poor exception handling (consistently throwing the same exception) 10. Possible violation of Single Responsibility Principle (SRP), as the method is responsible for multiple tasks. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void configure(Context context) { this.headerName = context.getString(CONFIG_MULTIPLEX_HEADER_NAME, DEFAULT_MULTIPLEX_HEADER); Map channelNameMap = getChannelNameMap(); defaultChannels = getChannelListFromNames( context.getString(CONFIG_DEFAULT_CHANNEL), channelNameMap); Map mapConfig = context.getSubProperties(CONFIG_PREFIX_MAPPING); channelMapping = new HashMap>(); for (String headerValue : mapConfig.keySet()) { List configuredChannels = getChannelListFromNames( mapConfig.get(headerValue), channelNameMap); //This should not go to default channel(s) //because this seems to be a bad way to configure. if (configuredChannels.size() == 0) { throw new FlumeException("No channel configured for when " + "header value is: " + headerValue); } if (channelMapping.put(headerValue, configuredChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } //If no mapping is configured, it is ok. //All events will go to the default channel(s). Map optionalChannelsMapping = context.getSubProperties(CONFIG_PREFIX_OPTIONAL + "."); optionalChannels = new HashMap>(); for (String hdr : optionalChannelsMapping.keySet()) { List confChannels = getChannelListFromNames( optionalChannelsMapping.get(hdr), channelNameMap); if (confChannels.isEmpty()) { confChannels = EMPTY_LIST; } //Remove channels from optional channels, which are already //configured to be required channels. List reqdChannels = channelMapping.get(hdr); //Check if there are required channels, else defaults to default channels if (reqdChannels == null || reqdChannels.isEmpty()) { reqdChannels = defaultChannels; } for (Channel c : reqdChannels) { if (confChannels.contains(c)) { confChannels.remove(c); } } if (optionalChannels.put(hdr, confChannels) != null) { throw new FlumeException("Selector channel configured twice"); } } } |
long method | Long method2 Feature envy3 Duplicate code (in the for loop)4 Confusing logic/naming (headerValue vs hdr)5 Magic numbers (CONFIG_PREFIX_OPTIONAL + "")6 Nested loops7 Use of isEmpty() instead of checking for size() == 08 Code comments indicating potential issues or bad practices9 Poor exception handling (consistently throwing the same exception) | t | f | t | 0 | 11896 | https://github.com/apache/flume/blob/7d3396f26dc1541e9d2a540d50d15a15c38acb74/flume-ng-core/src/main/java/org/apache/flume/channel/MultiplexingChannelSelector.java/#L83-L145 | 2 | 1763 | 11896 | minor | ||
| 2070 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public void Blit(SurfaceData src, SurfaceData dst, Composite comp, Region clip, int srcx, int srcy, int dstx, int dsty, int w, int h) { Raster srcRast = src.getRaster(srcx, srcy, w, h); IntegerComponentRaster icr = (IntegerComponentRaster) srcRast; int[] srcPix = icr.getDataStorage(); WritableRaster dstRast = (WritableRaster) dst.getRaster(dstx, dsty, w, h); ColorModel dstCM = dst.getColorModel(); Region roi = CustomComponent.getRegionOfInterest(src, dst, clip, srcx, srcy, dstx, dsty, w, h); SpanIterator si = roi.getSpanIterator(); Object dstPix = null; int srcScan = icr.getScanlineStride(); // assert(icr.getPixelStride() == 1); srcx -= dstx; srcy -= dsty; int[] span = new int[4]; while (si.nextSpan(span)) { int rowoff = (icr.getDataOffset(0) + (srcy + span[1]) * srcScan + (srcx + span[0])); for (int y = span[1]; y < span[3]; y++) { int off = rowoff; for (int x = span[0]; x < span[2]; x++) { dstPix = dstCM.getDataElements(srcPix[off++], dstPix); dstRast.setDataElements(x, y, dstPix); } rowoff += srcScan; } } // REMIND: We need to do something to make sure that dstRast // is put back to the destination (as in the native Release // function) // src.releaseRaster(srcRast); // NOP? // dst.releaseRaster(dstRast); } |
long method | Long method2 Feature envy | t | f | t | 0 | 13017 | https://github.com/SAP/SapMachine/blob/6e62561730c46dc5000c39665c43951832192ceb/src/java.desktop/share/classes/sun/java2d/loops/CustomComponent.java/#L171-L213 | 2 | 2070 | 13017 | minor | ||
| 1773 | { "message": "YES I found bad smells", "bad smells": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | data class | t | t | t | 0 | 11931 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 1773 | 11931 | major | ||
| 116 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private static class BeanRegistration { private final Class annotatedClass; @Nullable private final Supplier supplier; private final Class[] qualifiers; public BeanRegistration( Class annotatedClass, @Nullable Supplier supplier, Class[] qualifiers) { this.annotatedClass = annotatedClass; this.supplier = supplier; this.qualifiers = qualifiers; } public Class getAnnotatedClass() { return this.annotatedClass; } @Nullable @SuppressWarnings("rawtypes") public Supplier getSupplier() { return this.supplier; } public Class[] getQualifiers() { return this.qualifiers; } @Override public String toString() { return this.annotatedClass.getName(); } } |
data class | data class | t | t | t | 0 | 1503 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java/#L342-L376 | 1 | 116 | 1503 | major | ||
| 2198 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Nested loops 4. Lack of proper error handling 5. Excessive amount of parameters 6. Excessive commenting 7. Lack of proper abstraction 8. Use of primitive types instead of objects 9. Inconsistent naming conventions 10. Excessive code duplication or repetition | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public Iterator getRows(Session ses, SearchRow first, SearchRow last) { List rows = new ArrayList<>(); Collection nodes; SqlSystemViewColumnCondition idCond = conditionForColumn("NODE_ID", first, last); if (idCond.isEquality()) { try { UUID nodeId = uuidFromValue(idCond.valueForEquality()); ClusterNode node = nodeId == null ? null : ctx.discovery().node(nodeId); if (node != null) nodes = Collections.singleton(node); else nodes = Collections.emptySet(); } catch (Exception e) { nodes = Collections.emptySet(); } } else nodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes()); for (ClusterNode node : nodes) { if (node != null) { ClusterMetrics metrics = node.metrics(); rows.add( createRow( ses, node.id(), valueTimestampFromMillis(metrics.getLastUpdateTime()), metrics.getMaximumActiveJobs(), metrics.getCurrentActiveJobs(), metrics.getAverageActiveJobs(), metrics.getMaximumWaitingJobs(), metrics.getCurrentWaitingJobs(), metrics.getAverageWaitingJobs(), metrics.getMaximumRejectedJobs(), metrics.getCurrentRejectedJobs(), metrics.getAverageRejectedJobs(), metrics.getTotalRejectedJobs(), metrics.getMaximumCancelledJobs(), metrics.getCurrentCancelledJobs(), metrics.getAverageCancelledJobs(), metrics.getTotalCancelledJobs(), metrics.getMaximumJobWaitTime(), metrics.getCurrentJobWaitTime(), (long)metrics.getAverageJobWaitTime(), metrics.getMaximumJobExecuteTime(), metrics.getCurrentJobExecuteTime(), (long)metrics.getAverageJobExecuteTime(), metrics.getTotalJobsExecutionTime(), metrics.getTotalExecutedJobs(), metrics.getTotalExecutedTasks(), metrics.getTotalBusyTime(), metrics.getTotalIdleTime(), metrics.getCurrentIdleTime(), metrics.getBusyTimePercentage(), metrics.getIdleTimePercentage(), metrics.getTotalCpus(), metrics.getCurrentCpuLoad(), metrics.getAverageCpuLoad(), metrics.getCurrentGcCpuLoad(), metrics.getHeapMemoryInitialized(), metrics.getHeapMemoryUsed(), metrics.getHeapMemoryCommitted(), metrics.getHeapMemoryMaximum(), metrics.getHeapMemoryTotal(), metrics.getNonHeapMemoryInitialized(), metrics.getNonHeapMemoryUsed(), metrics.getNonHeapMemoryCommitted(), metrics.getNonHeapMemoryMaximum(), metrics.getNonHeapMemoryTotal(), metrics.getUpTime(), valueTimestampFromMillis(metrics.getStartTime()), valueTimestampFromMillis(metrics.getNodeStartTime()), metrics.getLastDataVersion(), metrics.getCurrentThreadCount(), metrics.getMaximumThreadCount(), metrics.getTotalStartedThreadCount(), metrics.getCurrentDaemonThreadCount(), metrics.getSentMessagesCount(), metrics.getSentBytesCount(), metrics.getReceivedMessagesCount(), metrics.getReceivedBytesCount(), metrics.getOutboundMessagesQueueSize() ) ); } } return rows.iterator(); } |
long method | Long method 2 Feature envy 3 Nested loops 4 Lack of proper error handling 5 Excessive amount of parameters 6 Excessive commenting 7 Lack of proper abstraction 8 Use of primitive types instead of objects 9 Inconsistent naming conventions | t | f | t | 0 | 13492 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sys/view/SqlSystemViewNodeMetrics.java/#L105-L200 | 2 | 2198 | 13492 | major | ||
| 2291 | {"message": "YES I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: protected static final class PersistenceWithIntOffset extends PersistenceWithIntOffsetNoLL { /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry prev; /** * Used by DiskRegion for compaction * * @since GemFire prPersistSprint1 */ private DiskEntry next; @Override public DiskEntry getPrev() { return this.prev; } @Override public DiskEntry getNext() { return this.next; } @Override public void setPrev(DiskEntry v) { this.prev = v; } @Override public void setNext(DiskEntry v) { this.next = v; } } |
data class | data class | t | t | t | 0 | 13942 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/main/java/org/apache/geode/internal/cache/DiskId.java/#L531-L564 | 1 | 2291 | 13942 | minor | ||
| 942 | YES I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public ResultSet getUpdateVTIResultSet(NoPutResultSet source) throws StandardException { Activation activation = source.getActivation(); getAuthorizer(activation).authorize(activation, Authorizer.SQL_WRITE_OP); return new UpdateVTIResultSet(source, activation); } |
feature envy | Feature envy | t | f | t | 0 | 8465 | https://github.com/apache/derby/blob/bd246fc89d4fce3f82f8344074ecb8a4713418df/java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/GenericResultSetFactory.java/#L188-L194 | 2 | 942 | 8465 | minor | ||
| 882 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void afterValue( K key, V value ) throws LdapException, CursorException { checkNotClosed(); /* * There is a subtle difference between after and before handling * with duplicate key values. Say we have the following tuples: * * (0, 0) * (1, 1) * (1, 2) * (1, 3) * (2, 2) * * If we request an after cursor on (1, 2). We must make sure that * the container cursor does not advance after the entry with key 1 * since this would result in us skip returning (1. 3) on the call to * next which will incorrectly return (2, 2) instead. * * So if the value is null in the element then we don't care about * this obviously since we just want to advance past the duplicate key * values all together. But when it is not null, then we want to * go right before this key instead of after it. */ if ( value == null ) { containerCursor.after( new Tuple>( key, null ) ); } else { containerCursor.before( new Tuple>( key, null ) ); } if ( containerCursor.next() ) { containerTuple.setBoth( containerCursor.get() ); DupsContainer values = containerTuple.getValue(); if ( values.isArrayTree() ) { ArrayTree set = values.getArrayTree(); dupsCursor = new ArrayTreeCursor<>( set ); } else { try { BTree tree = table.getBTree( values.getBTreeRedirect() ); dupsCursor = new KeyBTreeCursor<>( tree, table.getValueComparator() ); } catch ( IOException e ) { throw new CursorException( e ); } } if ( value == null ) { return; } // only advance the dupsCursor if we're on same key if ( table.getKeyComparator().compare( containerTuple.getKey(), key ) == 0 ) { dupsCursor.after( value ); } return; } clearValue(); containerTuple.setKey( null ); containerTuple.setValue( null ); } |
long method | long method | t | t | t | 0 | 8025 | https://github.com/apache/directory-server/blob/310007cc1c7eb5415f93bed67d5553bc70980820/jdbm-partition/src/main/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsCursor.java/#L174-L247 | 1 | 882 | 8025 | minor | ||
| 1437 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("SupervisorInfo("); boolean first = true; sb.append("time_secs:"); sb.append(this.time_secs); first = false; if (!first) sb.append(", "); sb.append("hostname:"); if (this.hostname == null) { sb.append("null"); } else { sb.append(this.hostname); } first = false; if (is_set_assignment_id()) { if (!first) sb.append(", "); sb.append("assignment_id:"); if (this.assignment_id == null) { sb.append("null"); } else { sb.append(this.assignment_id); } first = false; } if (is_set_used_ports()) { if (!first) sb.append(", "); sb.append("used_ports:"); if (this.used_ports == null) { sb.append("null"); } else { sb.append(this.used_ports); } first = false; } if (is_set_meta()) { if (!first) sb.append(", "); sb.append("meta:"); if (this.meta == null) { sb.append("null"); } else { sb.append(this.meta); } first = false; } if (is_set_scheduler_meta()) { if (!first) sb.append(", "); sb.append("scheduler_meta:"); if (this.scheduler_meta == null) { sb.append("null"); } else { sb.append(this.scheduler_meta); } first = false; } if (is_set_uptime_secs()) { if (!first) sb.append(", "); sb.append("uptime_secs:"); sb.append(this.uptime_secs); first = false; } if (is_set_version()) { if (!first) sb.append(", "); sb.append("version:"); if (this.version == null) { sb.append("null"); } else { sb.append(this.version); } first = false; } if (is_set_resources_map()) { if (!first) sb.append(", "); sb.append("resources_map:"); if (this.resources_map == null) { sb.append("null"); } else { sb.append(this.resources_map); } first = false; } if (is_set_server_port()) { if (!first) sb.append(", "); sb.append("server_port:"); sb.append(this.server_port); first = false; } sb.append(")"); return sb.toString(); } |
long method | long method, data class | t | t | t | data class | 0 | 10965 | https://github.com/apache/storm/blob/dc56e32f3dcdd9396a827a85029d60ed97474786/storm-client/src/jvm/org/apache/storm/generated/SupervisorInfo.java/#L969-L1059 | 1 | 1437 | 10965 | critical | |
| 1496 | YES, I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private ShardHandler getAndPrepShardHandler(SolrQueryRequest req, ResponseBuilder rb) { ShardHandler shardHandler = null; CoreContainer cc = req.getCore().getCoreContainer(); boolean isZkAware = cc.isZooKeeperAware(); rb.isDistrib = req.getParams().getBool(DISTRIB, isZkAware); if (!rb.isDistrib) { // for back compat, a shards param with URLs like localhost:8983/solr will mean that this // search is distributed. final String shards = req.getParams().get(ShardParams.SHARDS); rb.isDistrib = ((shards != null) && (shards.indexOf('/') > 0)); } if (rb.isDistrib) { shardHandler = shardHandlerFactory.getShardHandler(); shardHandler.prepDistributed(rb); if (!rb.isDistrib) { shardHandler = null; // request is not distributed after all and so the shard handler is not needed } } if (isZkAware) { String shardsTolerant = req.getParams().get(ShardParams.SHARDS_TOLERANT); boolean requireZkConnected = shardsTolerant != null && shardsTolerant.equals(ShardParams.REQUIRE_ZK_CONNECTED); ZkController zkController = cc.getZkController(); boolean zkConnected = zkController != null && ! zkController.getZkClient().getConnectionManager().isLikelyExpired(); if (requireZkConnected && false == zkConnected) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "ZooKeeper is not connected"); } else { NamedList headers = rb.rsp.getResponseHeader(); if (headers != null) { headers.add("zkConnected", zkConnected); } } } return shardHandler; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11125 | https://github.com/apache/lucene-solr/blob/bca22d58e2d126ec6d349d375d3ea028892104e1/solr/core/src/java/org/apache/solr/handler/component/SearchHandler.java/#L211-L248 | 2 | 1496 | 11125 | minor | ||
| 5536 | YES I found bad smells. The bad smells are: 1. Feature Envy; 2. Data Class. | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void setOptionalAttribute(BeanDefinitionBuilder builder, Map providedProperties, String propertyPrefix, String attributeValue, String attributeName) { String propertyKey; if ("username".equals(attributeName)) { String userKey = (propertyPrefix != null ? propertyPrefix + "user" : "user"); if (providedProperties.containsKey(userKey)) { propertyKey = userKey; } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeName : attributeName); } } else { propertyKey = (propertyPrefix != null ? propertyPrefix + attributeToPropertyMap.get(attributeName) : attributeToPropertyMap.get(attributeName)); } if (StringUtils.hasText(attributeValue)) { if (logger.isDebugEnabled()) { if ("password".equals(attributeName)) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value ******"); } else { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with attribute value " + attributeValue); } } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), attributeValue); } else if (providedProperties.containsKey(propertyKey)) { if (logger.isDebugEnabled()) { logger.debug("Registering optional attribute " + attributeToPropertyMap.get(attributeName) + " with property value " + ("password".equals(attributeName) ? "******" : providedProperties.get(propertyKey))); } builder.addPropertyValue(attributeToPropertyMap.get(attributeName), providedProperties.get(propertyKey)); } removeProvidedProperty(providedProperties, propertyKey); } |
feature envy | Feature Envy;2 Data Class | t | f | t | 0 | 6190 | https://github.com/spring-projects/spring-data-jdbc-ext/blob/9f19335f6f776ad36158cfaa0f5aad64333ce988/spring-data-oracle/src/main/java/org/springframework/data/jdbc/config/oracle/PoolingDataSourceBeanDefinitionParser.java/#L341-L388 | 1 | 5536 | 6190 | minor | ||
| 889 | { "output": "YES I found bad smells. the bad smells are: 1. Blob" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DruidPooledCallableStatement extends DruidPooledPreparedStatement implements CallableStatement { private CallableStatement stmt; public DruidPooledCallableStatement(DruidPooledConnection conn, PreparedStatementHolder holder) throws SQLException{ super(conn, holder); this.stmt = (CallableStatement) holder.statement; } public CallableStatement getCallableStatementRaw() { return stmt; } @Override public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public boolean wasNull() throws SQLException { try { return stmt.wasNull(); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(int parameterIndex) throws SQLException { try { return stmt.getString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(int parameterIndex) throws SQLException { try { return stmt.getBoolean(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(int parameterIndex) throws SQLException { try { return stmt.getByte(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(int parameterIndex) throws SQLException { try { return stmt.getShort(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(int parameterIndex) throws SQLException { try { return stmt.getInt(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(int parameterIndex) throws SQLException { try { return stmt.getLong(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(int parameterIndex) throws SQLException { try { return stmt.getFloat(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(int parameterIndex) throws SQLException { try { return stmt.getDouble(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override @Deprecated public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { try { return stmt.getBigDecimal(parameterIndex, scale); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(int parameterIndex) throws SQLException { try { return stmt.getBytes(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex) throws SQLException { try { return stmt.getDate(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex) throws SQLException { try { return stmt.getTime(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { try { return stmt.getTimestamp(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex) throws SQLException { try { Object obj = stmt.getObject(parameterIndex); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } private Object wrapObject(Object obj) { if (obj instanceof ResultSet) { ResultSet rs = (ResultSet) obj; DruidPooledResultSet poolableResultSet = new DruidPooledResultSet(this, rs); addResultSetTrace(poolableResultSet); obj = poolableResultSet; } return obj; } @Override public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { try { return stmt.getBigDecimal(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(int parameterIndex, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterIndex, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(int parameterIndex) throws SQLException { try { return stmt.getRef(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(int parameterIndex) throws SQLException { try { return stmt.getBlob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(int parameterIndex) throws SQLException { try { return stmt.getClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(int parameterIndex) throws SQLException { try { return stmt.getArray(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getDate(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTime(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterIndex, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterIndex, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.registerOutParameter(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(int parameterIndex) throws SQLException { try { return stmt.getURL(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public void setURL(String parameterName, java.net.URL val) throws SQLException { try { stmt.setURL(parameterName, val); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType) throws SQLException { try { stmt.setNull(parameterName, sqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setBoolean(String parameterName, boolean x) throws SQLException { try { stmt.setBoolean(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setByte(String parameterName, byte x) throws SQLException { try { stmt.setByte(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setShort(String parameterName, short x) throws SQLException { try { stmt.setShort(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setInt(String parameterName, int x) throws SQLException { try { stmt.setInt(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setLong(String parameterName, long x) throws SQLException { try { stmt.setLong(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setFloat(String parameterName, float x) throws SQLException { try { stmt.setFloat(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDouble(String parameterName, double x) throws SQLException { try { stmt.setDouble(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { try { stmt.setBigDecimal(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setString(String parameterName, String x) throws SQLException { try { stmt.setString(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBytes(String parameterName, byte x[]) throws SQLException { try { stmt.setBytes(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x) throws SQLException { try { stmt.setDate(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x) throws SQLException { try { stmt.setTime(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { try { stmt.setTimestamp(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType, scale); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { try { stmt.setObject(parameterName, x, targetSqlType); } catch (Throwable t) { throw checkException(t); } } @Override public void setObject(String parameterName, Object x) throws SQLException { try { stmt.setObject(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setDate(String parameterName, java.sql.Date x, Calendar cal) throws SQLException { try { stmt.setDate(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTime(String parameterName, java.sql.Time x, Calendar cal) throws SQLException { try { stmt.setTime(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) throws SQLException { try { stmt.setTimestamp(parameterName, x, cal); } catch (Throwable t) { throw checkException(t); } } @Override public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { try { stmt.setNull(parameterName, sqlType, typeName); } catch (Throwable t) { throw checkException(t); } } @Override public String getString(String parameterName) throws SQLException { try { return stmt.getString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public boolean getBoolean(String parameterName) throws SQLException { try { return stmt.getBoolean(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte getByte(String parameterName) throws SQLException { try { return stmt.getByte(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public short getShort(String parameterName) throws SQLException { try { return stmt.getShort(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public int getInt(String parameterName) throws SQLException { try { return stmt.getInt(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public long getLong(String parameterName) throws SQLException { try { return stmt.getLong(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public float getFloat(String parameterName) throws SQLException { try { return stmt.getFloat(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public double getDouble(String parameterName) throws SQLException { try { return stmt.getDouble(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public byte[] getBytes(String parameterName) throws SQLException { try { return stmt.getBytes(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName) throws SQLException { try { return stmt.getDate(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName) throws SQLException { try { return stmt.getTime(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { try { return stmt.getTimestamp(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName) throws SQLException { try { Object obj = stmt.getObject(parameterName); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public BigDecimal getBigDecimal(String parameterName) throws SQLException { try { return stmt.getBigDecimal(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Object getObject(String parameterName, java.util.Map> map) throws SQLException { try { Object obj = stmt.getObject(parameterName, map); return wrapObject(obj); } catch (Throwable t) { throw checkException(t); } } @Override public Ref getRef(String parameterName) throws SQLException { try { return stmt.getRef(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Blob getBlob(String parameterName) throws SQLException { try { return stmt.getBlob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Clob getClob(String parameterName) throws SQLException { try { return stmt.getClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public Array getArray(String parameterName) throws SQLException { try { return stmt.getArray(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Date getDate(String parameterName, Calendar cal) throws SQLException { try { return stmt.getDate(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Time getTime(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTime(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { try { return stmt.getTimestamp(parameterName, cal); } catch (Throwable t) { throw checkException(t); } } @Override public java.net.URL getURL(String parameterName) throws SQLException { try { return stmt.getURL(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(int parameterIndex) throws SQLException { try { return stmt.getRowId(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public RowId getRowId(String parameterName) throws SQLException { try { return stmt.getRowId(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setRowId(String parameterName, RowId x) throws SQLException { try { stmt.setRowId(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setNString(String parameterName, String value) throws SQLException { try { stmt.setNString(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { try { stmt.setNCharacterStream(parameterName, value, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, NClob value) throws SQLException { try { stmt.setNClob(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { try { stmt.setBlob(parameterName, inputStream, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader, long length) throws SQLException { try { stmt.setNClob(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(int parameterIndex) throws SQLException { try { return stmt.getNClob(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public NClob getNClob(String parameterName) throws SQLException { try { return stmt.getNClob(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { try { stmt.setSQLXML(parameterName, xmlObject); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(int parameterIndex) throws SQLException { try { return stmt.getSQLXML(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public SQLXML getSQLXML(String parameterName) throws SQLException { try { return stmt.getSQLXML(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(int parameterIndex) throws SQLException { try { return stmt.getNString(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public String getNString(String parameterName) throws SQLException { try { return stmt.getNString(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getNCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getNCharacterStream(String parameterName) throws SQLException { try { return stmt.getNCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(int parameterIndex) throws SQLException { try { return stmt.getCharacterStream(parameterIndex); } catch (Throwable t) { throw checkException(t); } } @Override public java.io.Reader getCharacterStream(String parameterName) throws SQLException { try { return stmt.getCharacterStream(parameterName); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, Blob x) throws SQLException { try { stmt.setBlob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Clob x) throws SQLException { try { stmt.setClob(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setAsciiStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x, long length) throws SQLException { try { stmt.setBinaryStream(parameterName, x, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader, long length) throws SQLException { try { stmt.setCharacterStream(parameterName, reader, length); } catch (Throwable t) { throw checkException(t); } } @Override public void setAsciiStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setAsciiStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setBinaryStream(String parameterName, java.io.InputStream x) throws SQLException { try { stmt.setBinaryStream(parameterName, x); } catch (Throwable t) { throw checkException(t); } } @Override public void setCharacterStream(String parameterName, java.io.Reader reader) throws SQLException { try { stmt.setCharacterStream(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setNCharacterStream(String parameterName, Reader value) throws SQLException { try { stmt.setNCharacterStream(parameterName, value); } catch (Throwable t) { throw checkException(t); } } @Override public void setClob(String parameterName, Reader reader) throws SQLException { try { stmt.setClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } @Override public void setBlob(String parameterName, InputStream inputStream) throws SQLException { try { stmt.setBlob(parameterName, inputStream); } catch (Throwable t) { throw checkException(t); } } @Override public void setNClob(String parameterName, Reader reader) throws SQLException { try { stmt.setNClob(parameterName, reader); } catch (Throwable t) { throw checkException(t); } } public T getObject(int parameterIndex, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } public T getObject(String parameterName, Class type) throws SQLException { throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") public T unwrap(Class iface) throws SQLException { if (iface == CallableStatement.class || iface == PreparedStatement.class) { if (stmt instanceof CallableStatementProxy) { return stmt.unwrap(iface); } return (T) stmt; } return super.unwrap(iface); } } |
blob | 1. blob | t | t | f | blob | 0 | 8078 | https://github.com/alibaba/druid/blob/768469fe4d1340efe1036453366a58c9ab7e30d1/src/main/java/com/alibaba/druid/pool/DruidPooledCallableStatement.java/#L40-L1089 | 1 | 889 | 8078 | critical | |
| 5025 | { "message": "YES, I found bad smells", "the bad smells are": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Socket { /* Standard socket defines */ public static final int SOCK_STREAM = 0; public static final int SOCK_DGRAM = 1; /* * apr_sockopt Socket option definitions */ public static final int APR_SO_LINGER = 1; /** Linger */ public static final int APR_SO_KEEPALIVE = 2; /** Keepalive */ public static final int APR_SO_DEBUG = 4; /** Debug */ public static final int APR_SO_NONBLOCK = 8; /** Non-blocking IO */ public static final int APR_SO_REUSEADDR = 16; /** Reuse addresses */ public static final int APR_SO_SNDBUF = 64; /** Send buffer */ public static final int APR_SO_RCVBUF = 128; /** Receive buffer */ public static final int APR_SO_DISCONNECTED = 256; /** Disconnected */ /** For SCTP sockets, this is mapped to STCP_NODELAY internally. */ public static final int APR_TCP_NODELAY = 512; public static final int APR_TCP_NOPUSH = 1024; /** No push */ /** This flag is ONLY set internally when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ public static final int APR_RESET_NODELAY = 2048; /** Set on non-blocking sockets (timeout != 0) on which the * previous read() did not fill a buffer completely. the next * apr_socket_recv() will first call select()/poll() rather than * going straight into read(). (Can also be set by an application to * force a select()/poll() call before the next read, in cases where * the app expects that an immediate read would fail.) */ public static final int APR_INCOMPLETE_READ = 4096; /** like APR_INCOMPLETE_READ, but for write */ public static final int APR_INCOMPLETE_WRITE = 8192; /** Don't accept IPv4 connections on an IPv6 listening socket. */ public static final int APR_IPV6_V6ONLY = 16384; /** Delay accepting of new connections until data is available. */ public static final int APR_TCP_DEFER_ACCEPT = 32768; /** Define what type of socket shutdown should occur. * apr_shutdown_how_e enum */ public static final int APR_SHUTDOWN_READ = 0; /** no longer allow read request */ public static final int APR_SHUTDOWN_WRITE = 1; /** no longer allow write requests */ public static final int APR_SHUTDOWN_READWRITE = 2; /** no longer allow read or write requests */ public static final int APR_IPV4_ADDR_OK = 0x01; public static final int APR_IPV6_ADDR_OK = 0x02; public static final int APR_UNSPEC = 0; public static final int APR_INET = 1; public static final int APR_INET6 = 2; public static final int APR_PROTO_TCP = 6; /** TCP */ public static final int APR_PROTO_UDP = 17; /** UDP */ public static final int APR_PROTO_SCTP = 132; /** SCTP */ /** * Enum to tell us if we're interested in remote or local socket * apr_interface_e */ public static final int APR_LOCAL = 0; public static final int APR_REMOTE = 1; /* Socket.get types */ public static final int SOCKET_GET_POOL = 0; public static final int SOCKET_GET_IMPL = 1; public static final int SOCKET_GET_APRS = 2; public static final int SOCKET_GET_TYPE = 3; /** * Create a socket. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The parent pool to use * @return The new socket that has been set up. * @throws Exception Error creating socket */ public static native long create(int family, int type, int protocol, long cont) throws Exception; /** * Shutdown either reading, writing, or both sides of a socket. * * This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * * @return the operation status */ public static native int shutdown(long thesocket, int how); /** * Close a socket. * @param thesocket The socket to close * @return the operation status */ public static native int close(long thesocket); /** * Destroy a pool associated with socket * @param thesocket The destroy */ public static native void destroy(long thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * This may be where we will find out if there is any other process * using the selected port. * @return the operation status */ public static native int bind(long sock, long sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. * @return the operation status */ public static native int listen(long sock, int backlog); /** * Accept a new connection request * @param sock The socket we are listening on. * @param pool The pool for the new socket. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long acceptx(long sock, long pool) throws Exception; /** * Accept a new connection request * @param sock The socket we are listening on. * @return A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @throws Exception Socket accept error */ public static native long accept(long sock) throws Exception; /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. * @return the operation status */ public static native int acceptfilter(long sock, String name, String args); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @return true if socket is at the OOB/urgent mark, * otherwise false. */ public static native boolean atmark(long sock); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. * @return the operation status */ public static native int connect(long sock, long sa); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param offset Offset in the byte buffer. * @param len The number of bytes to write; (-1) for full array. * @return The number of bytes sent */ public static native int send(long sock, byte[] buf, int offset, int len); /** * Send data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendb(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network without retry * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * * @param sock The socket to send the data over. * @param buf The Byte buffer which contains the data to be sent. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendib(long sock, ByteBuffer buf, int offset, int len); /** * Send data over a network using internally set ByteBuffer * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendbb(long sock, int offset, int len); /** * Send data over a network using internally set ByteBuffer * without internal retry. * @param sock The socket to send the data over. * @param offset The offset within the buffer array of the first buffer from * which bytes are to be retrieved; must be non-negative * and no larger than buf.length * @param len The maximum number of buffers to be accessed; must be non-negative * and no larger than buf.length - offset * @return The number of bytes sent */ public static native int sendibb(long sock, int offset, int len); /** * Send multiple packets of data over a network. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to send the data over. * @param vec The array from which to get the data to send. * @return The number of bytes sent */ public static native int sendv(long sock, byte[][] vec); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param offset Offset in the byte buffer. * @param len The length of the data to send * @return The number of bytes sent */ public static native int sendto(long sock, long where, int flags, byte[] buf, int offset, int len); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recv(long sock, byte[] buf, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvt(long sock, byte[] buf, int offset, int nbytes, long timeout); /** * Read data from a network. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If ≥ 0, the return value is the number of bytes read. Note a * non-blocking read with no data current available will return * {@link Status#EAGAIN} and EOF will return {@link Status#APR_EOF}. */ public static native int recvb(long sock, ByteBuffer buf, int offset, int nbytes); /** * Read data from a network using internally set ByteBuffer. * * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return If > 0, the return value is the number of bytes read. If == 0, * the return value indicates EOF and if < 0 the return value is the * error code. Note a non-blocking read with no data current * available will return {@link Status#EAGAIN} not zero. */ public static native int recvbb(long sock, int offset, int nbytes); /** * Read data from a network with timeout. * * * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbt(long sock, ByteBuffer buf, int offset, int nbytes, long timeout); /** * Read data from a network with timeout using internally set ByteBuffer * @param sock The socket to read the data from. * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @param timeout The socket timeout in microseconds. * @return the number of bytes received. */ public static native int recvbbt(long sock, int offset, int nbytes, long timeout); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param offset Offset in the byte buffer. * @param nbytes The number of bytes to read (-1) for full array. * @return the number of bytes received. */ public static native int recvfrom(long from, long sock, int flags, byte[] buf, int offset, int nbytes); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * * @param on Value for the option. * @return the operation status */ public static native int optSet(long sock, int opt, int on); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * * @return Socket option returned on the call. * @throws Exception An error occurred */ public static native int optGet(long sock, int opt) throws Exception; /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout in microseconds. * * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapses with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * * @return the operation status */ public static native int timeoutSet(long sock, long t); /** * Query socket timeout for the specified socket * @param sock The socket to query * @return Socket timeout returned from the query. * @throws Exception An error occurred */ public static native long timeoutGet(long sock) throws Exception; /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers. * * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. * @param sock The socket to which we're writing * @param file The open file from which to read * @param headers Array containing the headers to send * @param trailers Array containing the trailers to send * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent, including headers, * file, and trailers */ public static native long sendfile(long sock, long file, byte [][] headers, byte[][] trailers, long offset, long len, int flags); /** * Send a file without header and trailer arrays. * @param sock The socket to which we're writing * @param file The open file from which to read * @param offset Offset into the file where we should begin writing * @param len Number of bytes to send from the file * @param flags APR flags that are mapped to OS specific flags * @return Number of bytes actually sent */ public static native long sendfilen(long sock, long file, long offset, long len, int flags); /** * Create a child pool from associated socket pool. * @param thesocket The socket to use * @return a pointer to the pool * @throws Exception An error occurred */ public static native long pool(long thesocket) throws Exception; /** * Private method for getting the socket struct members * @param socket The socket to use * @param what Struct member to obtain * * SOCKET_GET_POOL - The socket pool * SOCKET_GET_IMPL - The socket implementation object * SOCKET_GET_APRS - APR socket * SOCKET_GET_TYPE - Socket type * * @return The structure member address */ private static native long get(long socket, int what); /** * Set internal send ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive sendbb calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setsbb(long sock, ByteBuffer buf); /** * Set internal receive ByteBuffer. * This function will preset internal Java ByteBuffer for * consecutive revcvbb/recvbbt calls. * @param sock The socket to use * @param buf The ByteBuffer */ public static native void setrbb(long sock, ByteBuffer buf); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @return the operation status */ public static native int dataSet(long sock, String key, Object data); /** * Return the data associated with the current socket * @param sock The currently open socket. * @param key The key to associate with the user data. * @return Data or null in case of error. */ public static native Object dataGet(long sock, String key); } |
data class | long method, data class | t | t | t | long method | 0 | 13928 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/jni/Socket.java/#L27-L629 | 1 | 5025 | 13928 | major | |
| 2177 | YES, I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception { ProjectFilesystem projectFilesystem = params.getCell().getFilesystem(); try (ProjectBuildFileParser parser = new DefaultProjectBuildFileParserFactory( new DefaultTypeCoercerFactory(), params.getConsole(), new ParserPythonInterpreterProvider( params.getCell().getBuckConfig(), params.getExecutableFinder()), params.getKnownRuleTypesProvider(), params.getManifestServiceSupplier(), params.getFileHashCache()) .createBuildFileParser( params.getBuckEventBus(), params.getCell(), params.getWatchman())) { /* * The super console does a bunch of rewriting over the top of the console such that * simultaneously writing to stdout and stderr in an interactive session is problematic. * (Overwritten characters, lines never showing up, etc). As such, writing to stdout directly * stops superconsole rendering (no errors appear). Because of all of this, we need to * just buffer the output and print it to stdout at the end fo the run. The downside * is that we have to buffer all of the output in memory, and it could potentially be large, * however, we'll just have to accept that tradeoff for now to get both error messages * from the parser, and the final output */ try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(new BufferedOutputStream(byteOut))) { for (String pathToBuildFile : getArguments()) { // Print a comment with the path to the build file. out.printf("# %s\n\n", pathToBuildFile); // Resolve the path specified by the user. Path path = Paths.get(pathToBuildFile); if (!path.isAbsolute()) { Path root = projectFilesystem.getRootPath(); path = root.resolve(path); } // Parse the rules from the build file. ImmutableMap> rawRules = parser.getBuildFileManifest(path).getTargets(); // Format and print the rules from the raw data, filtered by type. ImmutableSet types = getTypes(); Predicate includeType = type -> types.isEmpty() || types.contains(type); printRulesToStdout(out, rawRules, includeType); } // Make sure we tell the event listener to flush, otherwise there is a race condition where // the event listener might not have flushed, we dirty the stream, and then it will not // render the last frame (see {@link SuperConsoleEventListener}) params.getBuckEventBus().post(new FlushConsoleEvent()); out.close(); params.getConsole().getStdOut().write(byteOut.toByteArray()); } } return ExitCode.SUCCESS; } |
long method | Long method2 Feature envy | t | f | t | 0 | 13408 | https://github.com/facebook/buck/blob/1bc8d383ea5cb153ca9bf4f2807e6be498648523/src/com/facebook/buck/cli/AuditRulesCommand.java/#L90-L148 | 2 | 2177 | 13408 | minor | ||
| 407 | YES, I found bad smells the bad smells are: 1. Long method 2. Long parameter list 3. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static byte[] decodeUrl( byte[] bytes ) throws UrlDecoderException { if ( bytes == null ) { return Strings.EMPTY_BYTES; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for ( int i = 0; i < bytes.length; i++ ) { int b = bytes[i]; if ( b == '%' ) { try { int u = Character.digit( ( char ) bytes[++i], 16 ); int l = Character.digit( ( char ) bytes[++i], 16 ); if ( ( u == -1 ) || ( l == -1 ) ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ) ); } buffer.write( ( char ) ( ( u << 4 ) + l ) ); } catch ( ArrayIndexOutOfBoundsException aioobe ) { throw new UrlDecoderException( I18n.err( I18n.ERR_13040_INVALID_URL_ENCODING ), aioobe ); } } else { buffer.write( b ); } } return buffer.toByteArray(); } |
long method | Long method2 Long parameter list3 Feature envy | t | f | t | 0 | 4155 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/url/LdapUrl.java/#L1067-L1106 | 2 | 407 | 4155 | minor | ||
| 1101 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Blob", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public void main(List trees) { // complete the javac AST with a completed ceylon model timer.startTask("prepareForTypeChecking"); prepareForTypeChecking(trees); timer.endTask(); List javaTrees = List.nil(); List ceylonTrees = List.nil(); // split them in two sets: java and ceylon for(JCCompilationUnit tree : trees){ if(tree instanceof CeylonCompilationUnit) ceylonTrees = ceylonTrees.prepend(tree); else javaTrees = javaTrees.prepend(tree); } timer.startTask("Enter on Java trees"); boolean needsModelReset = isBootstrap; // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking if(!javaTrees.isEmpty()){ setupImportedPackagesForJavaTrees(javaTrees); hasJavaAndCeylonSources = true; needsModelReset = true; } // this is false if we're in an APT round where we did not generate the trees if(!compiler.isAddModuleTrees()){ setupImportedPackagesForJavaTrees(ceylonTrees); } if(isBootstrap || hasJavaAndCeylonSources){ super.main(trees); } // now we can type-check the Ceylon code List packageInfo = completeCeylonTrees(trees); trees = trees.prependList(packageInfo); ceylonTrees = ceylonTrees.prependList(packageInfo); if(compiler.isHadRunTwiceException()){ needsModelReset = true; } if(needsModelReset){ // bootstrapping the language module is a bit more complex resetAndRunEnterAgain(trees); }else{ timer.startTask("Enter on Ceylon trees"); // and complete their new trees try { sourceLanguage.push(Language.CEYLON); super.main(ceylonTrees); } finally { sourceLanguage.pop(); } timer.endTask(); } } |
long method | blob, long method | t | t | t | blob | 0 | 9839 | https://github.com/eclipse/ceylon/blob/d3994d6cd120c4df85952cd9432123b413cfd65a/compiler-java/src/org/eclipse/ceylon/compiler/java/loader/CeylonEnter.java/#L203-L255 | 1 | 1101 | 9839 | major | |
| 5271 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: if (!experimentCatalog.isExist(ExperimentCatalogModelType.EXPERIMENT, airavataExperimentId)) { logger.error(airavataExperimentId, "Update request failed, Experiment {} doesn't exist.", airavataExperimentId); throw new RegistryServiceException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); if (experimentStatus != null){ ExperimentState experimentState = experimentStatus.getState(); switch (experimentState){ case CREATED: case VALIDATED: if(experiment.getUserConfigurationData() != null && experiment.getUserConfigurationData() .getComputationalResourceScheduling() != null){ String compResourceId = experiment.getUserConfigurationData() .getComputationalResourceScheduling().getResourceHostId(); ComputeResourceDescription computeResourceDescription = appCatalog.getComputeResource() .getComputeResource(compResourceId); if(!computeResourceDescription.isEnabled()){ logger.error("Compute Resource is not enabled by the Admin!"); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Compute Resource is not enabled by the Admin!"); throw exception; } } experimentCatalog.update(ExperimentCatalogModelType.EXPERIMENT, experiment, airavataExperimentId); logger.debug(airavataExperimentId, "Successfully updated experiment {} ", experiment.getExperimentName()); break; default: logger.error(airavataExperimentId, "Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while updating experiment. Update experiment is only valid for experiments " + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + "experiment is in one of above statuses... "); throw exception; } } } catch (RegistryException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } catch (AppCatalogException e) { logger.error(airavataExperimentId, "Error while updating experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); throw exception; } } /** * * * * Create New Experiment |
long method | long method | t | t | t | 0 | 14741 | https://github.com/apache/airavata/blob/391843a00eefa7b6213e845f2f044b4e042894d5/modules/registry/registry-server/registry-api-service/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java/#L3124-L3178 | 1 | 5271 | 14741 | minor | ||
| 385 | { "message": "YES I found bad smells", "bad smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | data class, long method | t | t | t | long method | 0 | 3938 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 1 | 385 | 3938 | minor | |
| 729 | YES I found bad smells1. Long method 2. Feature envy 3. Message chain | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | Long method2 Feature envy 3 Message chain | t | f | t | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 2 | 729 | 6854 | minor | ||
| 1559 | YES I found bad smells The bad smells are: 1. Long method 2. Feature envy 3. Duplicate code (in the if conditions for different instances of Length) | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: public float computeTableUnit(PercentBaseContext percentBaseContext, int contentAreaIPD) { int sumCols = 0; float factors = 0; float unit = 0; /* calculate the total width (specified absolute/percentages), * and work out the total number of factors to use to distribute * the remaining space (if any) */ for (Object colWidth1 : colWidths) { Length colWidth = (Length) colWidth1; if (colWidth != null) { sumCols += colWidth.getValue(percentBaseContext); if (colWidth instanceof RelativeNumericProperty) { factors += ((RelativeNumericProperty) colWidth).getTableUnits(); } else if (colWidth instanceof TableColLength) { factors += ((TableColLength) colWidth).getTableUnits(); } } } /* distribute the remaining space over the accumulated * factors (if any) */ if (factors > 0) { if (sumCols < contentAreaIPD) { unit = (contentAreaIPD - sumCols) / factors; } else { log.warn("No space remaining to distribute over columns."); } } return unit; } |
long method | Long method2 Feature envy3 Duplicate code (in the if conditions for different instances of Length) | t | f | t | 0 | 11300 | https://github.com/apache/fop/blob/caced35327f6b6d6eeac2a13543f3c458e902101/fop-core/src/main/java/org/apache/fop/layoutmgr/table/ColumnSetup.java/#L201-L235 | 2 | 1559 | 11300 | minor | ||
| 307 | { "message": "YES, I found bad smells", "detected_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int getDVDTotalTitles() { if (bdp != null) return bdp.getNumTitles(); return 0; } |
feature envy | long method, feature envy | t | t | t | long method | 0 | 3199 | https://github.com/google/sagetv/blob/a35e3a450b4c0134cb097b9e7de76dca08eb6654/java/sage/MiniPlayer.java/#L2879-L2884 | 1 | 307 | 3199 | critical | |
| 3987 | { "response": "YES I found bad smells", "bad smells are": ["Long Method", "Blob"] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public BatchResponsePart executeChangeSet(final BatchHandler handler, final List requests) throws ODataException { List responses = new ArrayList(); try { oDataJPAContext.getODataJPATransaction().begin(); for (ODataRequest request : requests) { oDataJPAContext.setODataContext(getContext()); ODataResponse response = handler.handleRequest(request); if (response.getStatus().getStatusCode() >= HttpStatusCodes.BAD_REQUEST.getStatusCode()) { // Rollback oDataJPAContext.getODataJPATransaction().rollback(); List errorResponses = new ArrayList(1); errorResponses.add(response); return BatchResponsePart.responses(errorResponses).changeSet(false).build(); } responses.add(response); } oDataJPAContext.getODataJPATransaction().commit(); return BatchResponsePart.responses(responses).changeSet(true).build(); } catch (Exception e) { throw new ODataException("Error on processing request content:" + e.getMessage(), e); } finally { close(true); } } |
long method | long method, blob | t | t | t | blob | 0 | 10502 | https://github.com/apache/olingo-odata2/blob/c5e9fdf569b5e2e50f5670c91013db8f9ae1d950/odata2-jpa-processor/jpa-api/src/main/java/org/apache/olingo/odata2/jpa/processor/api/ODataJPADefaultProcessor.java/#L270-L297 | 1 | 3987 | 10502 | minor | |
| 1145 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public boolean makeAcquisitionUnstealable(final MessageInstanceConsumer consumer) { EntryState state = _state; if(state instanceof StealableConsumerAcquiredState && ((StealableConsumerAcquiredState) state).getConsumer() == consumer) { UnstealableConsumerAcquiredState unstealableState = ((StealableConsumerAcquiredState) state).getUnstealableState(); boolean updated = _stateUpdater.compareAndSet(this, state, unstealableState); if(updated) { notifyStateChange(state, unstealableState); } return updated; } return state instanceof UnstealableConsumerAcquiredState && ((UnstealableConsumerAcquiredState) state).getConsumer() == consumer; } |
long method | long method | t | t | t | 0 | 10111 | https://github.com/apache/qpid-broker-j/blob/4c4400b98a5a8493cfb9e5dbb21c97175f433a62/broker-core/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java/#L336-L353 | 1 | 1145 | 10111 | minor | ||
| 1195 | YES I found bad smells the bad smells are: 1. Long method, 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException { if (claim == null) { if (append) { return 0L; } Files.createFile(destination); return 0L; } final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE; try (final InputStream in = read(claim); final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) { if (offset > 0) { StreamUtils.skip(in, offset); } StreamUtils.copy(in, destinationStream, length); return length; } } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10266 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/repository/VolatileContentRepository.java/#L397-L418 | 2 | 1195 | 10266 | minor | |
| 2110 | { "response": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void grantOrRevokeRoleOnGroup(List hivePrincipals, List roles, HivePrincipal grantorPrinc, boolean isGrant) throws HiveAuthzPluginException, HiveAccessControlException { try { sentryClient = getSentryClient(); // get principals Set groups = Sets.newHashSet(); for (HivePrincipal principal : hivePrincipals) { if (principal.getType() != HivePrincipalType.GROUP) { String msg = SentryHiveConstants.GRANT_REVOKE_NOT_SUPPORTED_FOR_PRINCIPAL + principal.getType(); throw new HiveAuthzPluginException(msg); } groups.add(principal.getName()); } // grant/revoke role to/from principals for (String roleName : roles) { if (isGrant) { sentryClient.grantRoleToGroups(grantorPrinc.getName(), roleName, groups); } else { sentryClient.revokeRoleFromGroups(grantorPrinc.getName(), roleName, groups); } } } catch (SentryAccessDeniedException e) { HiveOperation hiveOp = isGrant ? HiveOperation.GRANT_ROLE : HiveOperation.REVOKE_ROLE; executeOnFailureHooks(hiveOp, e); } catch (SentryUserException e) { String msg = "Error when sentryClient grant/revoke role:" + e.getMessage(); executeOnErrorHooks(msg, e); } finally { if (sentryClient != null) { sentryClient.close(); } } } |
long method | long method | t | t | t | 0 | 13182 | https://github.com/apache/incubator-sentry/blob/4643f988a5e0ce2b9749e6365edea3a16482de86/sentry-binding/sentry-binding-hive-v2/src/main/java/org/apache/sentry/binding/hive/v2/authorizer/DefaultSentryAccessController.java/#L479-L515 | 1 | 2110 | 13182 | minor | ||
| 2597 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override public Collection validate(final ValidationContext validationContext, final CredentialsStrategy primaryStrategy) { boolean thisIsSelectedStrategy = this == primaryStrategy; Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean(); if (!thisIsSelectedStrategy && useStrategy) { String failureFormat = "property %1$s cannot be used with %2$s"; Collection validationFailureResults = new ArrayList(); String message = String.format(failureFormat, strategyProperty.getDisplayName(), primaryStrategy.getName()); validationFailureResults.add(new ValidationResult.Builder() .subject(strategyProperty.getDisplayName()) .valid(false) .explanation(message).build()); return validationFailureResults; } return null; } |
long method | 1. long method, 2. feature envy | t | t | t | 2. feature envy | 0 | 15009 | https://github.com/apache/nifi/blob/c8eff590efa3babcda0b755009224dcac168708b/nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/credentials/provider/factory/strategies/AbstractBooleanCredentialsStrategy.java/#L51-L68 | 1 | 2597 | 15009 | minor | |
| 379 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy 3. Switch statement 4. Possible lack of comparison strategy for different cases 5. Use of instanceof operator 6. Use of type-unsafe comparison between different types (numbers and strings) 7. Lack of proper comments/documentation 8. Unclear and potentially misleading variable names such as "o1" and "o2" 9. Potential for code duplication due to nested if/else statements 10. Use of raw type Collection instead of parametrized type | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: static boolean evaluateImpl(Object o1, Object o2) { // TODO: maybe we need a comparison "strategy" here, instead of // a switch of all possible cases? ... there were other requests for // more relaxed type-unsafe comparison (e.g. numbers to strings) if (o1 == null && o2 == null) { return true; } else if (o1 != null) { // Per CAY-419 we perform 'in' comparison if one object is a list, and other is not if (o2 instanceof Collection) { for (Object element : ((Collection) o2)) { if (element != null && Evaluator.evaluator(element).eq(element, o1)) { return true; } } return false; } return Evaluator.evaluator(o1).eq(o1, o2); } return false; } |
long method | Long method2 Feature envy3 Switch statement4 Possible lack of comparison strategy for different cases5 Use of instanceof operator6 Use of type-unsafe comparison between different types (numbers and strings)7 Lack of proper comments/documentation8 Unclear and potentially misleading variable names such as "o | t | f | t | 0 | 3905 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-server/src/main/java/org/apache/cayenne/exp/parser/ASTEqual.java/#L76-L97 | 2 | 379 | 3905 | minor | ||
| 632 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public int hashCode() { int hash = 37; if ( baseDn != null ) { hash = hash * 17 + baseDn.hashCode(); } hash = hash * 17 + aliasDerefMode.hashCode(); hash = hash * 17 + scope.hashCode(); hash = hash * 17 + Long.valueOf( sizeLimit ).hashCode(); hash = hash * 17 + timeLimit; hash = hash * 17 + ( typesOnly ? 0 : 1 ); if ( attributes != null ) { hash = hash * 17 + attributes.size(); // Order doesn't matter, thus just add hashCode for ( String attr : attributes ) { if ( attr != null ) { hash = hash + attr.hashCode(); } } } BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); filterNode.accept( visitor ); hash = hash * 17 + filterNode.toString().hashCode(); hash = hash * 17 + super.hashCode(); return hash; } |
long method | Long method2 Feature envy | t | f | t | 0 | 6293 | https://github.com/apache/directory-ldap-api/blob/5b93e102556ad2191b5d30411708410d1b1a9d71/ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/SearchRequestImpl.java/#L373-L409 | 2 | 632 | 6293 | major | ||
| 2465 | {"response": "YES I found bad smells the bad smells are: 1. Data Class"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: class Segment { private byte segmentType; Segment(byte segmentType) { this.segmentType = segmentType; } /** * Returns the segmentType value. * * @return byte segmentType value. */ public byte getSegmentType() { return segmentType; } } |
data class | 1. data class | t | t | t | 0 | 14561 | https://github.com/Microsoft/mssql-jdbc/blob/84484edf7944de56749fd2648d0af2ffa2459b7a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSpatialDatatype.java/#L1932-L1947 | 1 | 2465 | 14561 | major | ||
| 1362 | YES I found bad smells, the bad smells are: 1. Long method, 2. Feature envy. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private String formatQueryString(final String projectUri, final String[] args) { final StringBuffer result = new StringBuffer(); if (projectUri != null) { if (isCompatibleMode) { result.append("puri="); //$NON-NLS-1$ result.append(URLEncode.encode(projectUri.toString())); } else { final ArtifactID artifactID = new ArtifactID(projectUri); result.append("pguid="); //$NON-NLS-1$ result.append(URLEncode.encode(artifactID.getToolSpecificID())); } } else if (!isCompatibleMode) { result.append("pcguid="); //$NON-NLS-1$ result.append(URLEncode.encode(collectionId.toString())); } for (int i = 0; i < args.length - 1; i += 2) { final String name = args[i]; final String value = args[i + 1]; if (name != null) { if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(name)); } if (value != null) { if (name != null) { result.append('='); } else if (result.length() > 0) { result.append('&'); } result.append(URLEncode.encode(value)); } } return result.toString(); } |
feature envy | Long method, 2 Feature envy | t | f | t | . Long method | 0 | 10779 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/util/TSWAHyperlinkBuilder.java/#L518-L559 | 2 | 1362 | 10779 | minor | |
| 5745 | { "response": "YES I found bad smells", "the bad smells are": { "1. Long method": true, "2. Feature envy": true } } | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public void addOptionValues(List optionValues, Map context, Delegator delegator) { // first expand any conditions that need expanding based on the current context EntityCondition findCondition = null; if (UtilValidate.isNotEmpty(this.constraintList)) { List expandedConditionList = new LinkedList<>(); for (EntityFinderUtil.Condition condition : constraintList) { ModelEntity modelEntity = delegator.getModelEntity(this.entityName); if (modelEntity == null) { throw new IllegalArgumentException("Error in entity-options: could not find entity [" + this.entityName + "]"); } EntityCondition createdCondition = condition.createCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); if (createdCondition != null) { expandedConditionList.add(createdCondition); } } findCondition = EntityCondition.makeCondition(expandedConditionList); } try { Locale locale = UtilMisc.ensureLocale(context.get("locale")); ModelEntity modelEntity = delegator.getModelEntity(this.entityName); Boolean localizedOrderBy = UtilValidate.isNotEmpty(this.orderByList) && ModelUtil.isPotentialLocalizedFields(modelEntity, this.orderByList); List values = null; if (!localizedOrderBy) { values = delegator.findList(this.entityName, findCondition, null, this.orderByList, null, this.cache); } else { //if entity has localized label values = delegator.findList(this.entityName, findCondition, null, null, null, this.cache); values = EntityUtil.localizedOrderBy(values, this.orderByList, locale); } // filter-by-date if requested if ("true".equals(this.filterByDate)) { values = EntityUtil.filterByDate(values, true); } else if (!"false".equals(this.filterByDate)) { // not explicitly true or false, check to see if has fromDate and thruDate, if so do the filter if (modelEntity != null && modelEntity.isField("fromDate") && modelEntity.isField("thruDate")) { values = EntityUtil.filterByDate(values, true); } } for (GenericValue value : values) { // add key and description with string expansion, ie expanding ${} stuff, passing locale explicitly to expand value string because it won't be found in the Entity MapStack localContext = MapStack.create(context); // Rendering code might try to modify the GenericEntity instance, // so we make a copy of it. Map genericEntityClone = UtilGenerics.cast(value.clone()); localContext.push(genericEntityClone); // expand with the new localContext, which is locale aware String optionDesc = this.description.expandString(localContext, locale); Object keyFieldObject = value.get(this.getKeyFieldName()); if (keyFieldObject == null) { throw new IllegalArgumentException( "The entity-options identifier (from key-name attribute, or default to the field name) [" + this.getKeyFieldName() + "], may not be a valid key field name for the entity [" + this.entityName + "]."); } String keyFieldValue = keyFieldObject.toString(); optionValues.add(new OptionValue(keyFieldValue, optionDesc)); } } catch (GenericEntityException e) { Debug.logError(e, "Error getting entity options in form", module); } } |
feature envy | 1. long method: true, 2. feature envy: true | t | t | t | 1. long method: true | 0 | 14138 | https://github.com/apache/ofbiz-framework/blob/b1304439219bb04c396f5d000bec9c5fbb194b59/framework/widget/src/main/java/org/apache/ofbiz/widget/model/ModelFormField.java/#L1962-L2032 | 2 | 5745 | 14138 | minor | |
| 2095 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class JarModule { private ModuleRevisionId mrid; private File jar; public JarModule(ModuleRevisionId mrid, File jar) { this.mrid = mrid; this.jar = jar; } public File getJar() { return jar; } public ModuleRevisionId getMrid() { return mrid; } public String toString() { return jar + " " + mrid; } } |
data class | data class | t | t | t | 0 | 13145 | https://github.com/apache/ant-ivy/blob/4ffcf8f06f238b17e78e8033c3e8278833e452eb/src/java/org/apache/ivy/tools/analyser/JarModule.java/#L24-L46 | 1 | 2095 | 13145 | major | ||
| 729 | { "message": "YES, I found bad smells", "detected_bad_smells": [ "Long Method", "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: InitializeParams get(String id) throws LanguageServerException { InitializeParams initializeParams = new InitializeParams(); LOG.debug("Initialize params constructing: started"); Boolean locality = localityRegistry.get(id); LOG.debug("Locality: {}", locality); Integer processId = locality ? ProcessIdProvider.get() : null; initializeParams.setProcessId(processId); LOG.debug("Process id: {}", processId); String projectsRoot = projectsRootRegistry.getOrNull(id); String rootPath; if (projectsRoot != null) { rootPath = projectsRoot; } else { rootPath = Paths.get(rootUri).toAbsolutePath().toString(); } initializeParams.setRootPath(rootPath); LOG.debug("Root path: {}", rootPath); String rootUri; if (projectsRoot != null) { rootUri = Paths.get(projectsRoot).toUri().toString(); } else { rootUri = this.rootUri.toString(); } initializeParams.setRootUri(rootUri); LOG.debug("Root URI: {}", rootUri); ClientCapabilities capabilities = ClientCapabilitiesProvider.get(); initializeParams.setCapabilities(capabilities); LOG.debug("Client capabilities: {}", capabilities); String clientName = ClientCapabilitiesProvider.CLIENT_NAME; initializeParams.setClientName(clientName); LOG.debug("Client name: {}", clientName); LOG.debug("Initialize params constructing: finished"); return initializeParams; } |
long method | long method, data class | t | t | t | data class | 0 | 6854 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/wsagent/che-core-api-languageserver/src/main/java/org/eclipse/che/api/languageserver/InitializeParamsProvider.java/#L73-L114 | 1 | 729 | 6854 | minor | |
| 5189 | { "response": "YES I found bad smells", "bad_smells": [ "Long Method", "Feature Envy" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: None |
long method | long method, feature envy | t | t | t | feature envy | 0 | 14509 | https://github.com/apache/hive/blob/2fa22bf360898dc8fd1408bfcc96e1c6aeaf9a53/standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/ThriftHiveMetastore.java/#L65076-L65111 | 1 | 5189 | 14509 | minor | |
| 1180 | {"response": "YES, I found bad smells", "bad smells are": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class ShuffleWriteMetrics { private long bytesWritten; private long recordsWritten; private long writeTime; public long getBytesWritten () { return bytesWritten; } public void setBytesWritten (long bytesWritten) { this.bytesWritten = bytesWritten; } public long getRecordsWritten () { return recordsWritten; } public void setRecordsWritten (long recordsWritten) { this.recordsWritten = recordsWritten; } public long getWriteTime () { return writeTime; } public void setWriteTime (long writeTime) { this.writeTime = writeTime; } } |
data class | data class | t | t | t | 0 | 10230 | https://github.com/Microsoft/azure-tools-for-java/blob/d121e8ac9cc3ab400e5b49c8b372280ae332f3fb/Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/sdk/rest/spark/task/ShuffleWriteMetrics.java/#L24-L60 | 1 | 1180 | 10230 | critical | ||
| 754 | {"response": "YES I found bad smells", "bad smells are": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Override @SuppressWarnings("unchecked") public int executeUpdate(final String inSql) throws SQLException { this.sql = inSql; if (this.sql == null) { throw new SQLException("sql is null"); } trimSQL(); if (this.sql.length() == 0) { throw new SQLException("empty sql"); } String lowcaseSql = this.sql.toLowerCase(); Object req = null; // TODO use patterns if (lowcaseSql.startsWith("create domain") || lowcaseSql.startsWith("create table")) { //$NON-NLS-1$ int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); req = new CreateDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete domain") || lowcaseSql.startsWith("delete table") //$NON-NLS-1$ || lowcaseSql.startsWith("drop table")) { int pos = this.sql.lastIndexOf(" "); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(pos + 1).trim(), DELIMITED_IDENTIFIER_QUOTE); List pending = this.conn.getPendingColumns(domain); if (pending != null) { pending = new ArrayList<>(pending); for (String attr : pending) { this.conn.removePendingColumn(domain, attr); } } req = new DeleteDomainRequest().withDomainName(domain); } else if (lowcaseSql.startsWith("delete from")) { req = prepareDeleteRowRequest(); } else if (lowcaseSql.startsWith("alter table ")) { req = prepareDropAttributeRequest(); } else if (lowcaseSql.startsWith("insert ")) { req = prepareInsertRequest(); } else if (lowcaseSql.startsWith("update ")) { req = prepareUpdateRequest(); } else if (lowcaseSql.startsWith("create testdomain ")) { req = new ArrayList<>(); String domain = convertSQLIdentifierToCatalogFormat(this.sql.substring(this.sql.lastIndexOf(" ") + 1).trim(), //$NON-NLS-1$ DELIMITED_IDENTIFIER_QUOTE); ((List) req).add(new CreateDomainRequest().withDomainName(domain)); ReplaceableAttribute attr = new ReplaceableAttribute().withName("attr1").withValue("val1").withReplace(Boolean.TRUE); for (int i = 0; i < 570; i++) { ((List) req).add(new PutAttributesRequest().withDomainName(domain).withItemName("item" + i).withAttributes(attr)); } } if (req != null) { int result = executeSDBRequest(req); if (this.params != null) { for (Object obj : this.params) { if (obj instanceof SimpleDBItemName) { ((SimpleDBItemName) obj).setPersisted(true); } } } return result; } throw new SQLException("unsupported update: " + this.sql); } |
long method | long method | t | t | t | 0 | 7039 | https://github.com/aws/aws-toolkit-eclipse/blob/49026f53fdd4f80a7fb997c9e40fe6e638a26edc/bundles/com.amazonaws.eclipse.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/JdbcStatement.java/#L432-L502 | 1 | 754 | 7039 | minor | ||
| 229 | {"message": "YES I found bad smells", "bad smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransformIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The transformer being used */ private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} and * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- @Override public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ @Override public O next() { return transform(iterator.next()); } @Override public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } //----------------------------------------------------------------------- /** * Gets the transformer this iterator is using. * * @return the transformer. */ public Transformer getTransformer() { return transformer; } /** * Sets the transformer this the iterator to use. * A null transformer is a no-op transformer. * * @param transformer the transformer to use */ public void setTransformer(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } |
data class | data class, long method | t | t | t | long method | 0 | 2506 | https://github.com/apache/commons-collections/blob/bb0781551c7f1d7ddd28733acff95e1f130e766c/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.java/#L28-L146 | 1 | 229 | 2506 | minor | |
| 5765 | } YES I found bad smells the bad smells are: 1. Long method, 2.Feature envy | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: } private boolean mergeMap(Map fragmentMap, Map mainMap, Map tempMap, WebXml fragment, String mapName) { for (Entry entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; |
long method | Long method, 2Feature envy | t | f | t | 2.Feature envy | 0 | 14654 | https://github.com/apache/tomcat/blob/a9c1a0661198d9ba37c1facd8385fe05d538c4ad/java/org/apache/tomcat/util/descriptor/web/WebXml.java/#L1961-L1987 | 1 | 5765 | 14654 | minor | |
| 866 | { "message": "YES I found bad smells", "bad smells are": [ "1. Long Method", "2. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private XMLEvent expectTag(String expected, boolean allowEnd) throws IOException { XMLEvent ev = null; while (true) { try { ev = events.nextEvent(); } catch (XMLStreamException e) { throw new IOException("Expecting " + expected + ", but got XMLStreamException", e); } switch (ev.getEventType()) { case XMLEvent.ATTRIBUTE: throw new IOException("Got unexpected attribute: " + ev); case XMLEvent.CHARACTERS: if (!ev.asCharacters().isWhiteSpace()) { throw new IOException("Got unxpected characters while " + "looking for " + expected + ": " + ev.asCharacters().getData()); } break; case XMLEvent.END_ELEMENT: if (!allowEnd) { throw new IOException("Got unexpected end event " + "while looking for " + expected); } return ev; case XMLEvent.START_ELEMENT: if (!expected.startsWith("[")) { if (!ev.asStartElement().getName().getLocalPart(). equals(expected)) { throw new IOException("Failed to find <" + expected + ">; " + "got " + ev.asStartElement().getName().getLocalPart() + " instead."); } } return ev; default: // Ignore other event types like comment, etc. if (LOG.isTraceEnabled()) { LOG.trace("Skipping XMLEvent of type " + ev.getEventType() + "(" + ev + ")"); } break; } } } |
long method | 1. long method, 2. blob | t | t | t | 2. blob | 0 | 7932 | https://github.com/apache/hadoop/blob/128dd91e10080bdcbcd7d555fa3c4105e55a6b51/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/OfflineImageReconstructor.java/#L184-L229 | 1 | 866 | 7932 | minor | |
| 2304 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public void configure(TestElement el) { setName(el.getName()); Arguments arguments = (Arguments) el.getProperty(HTTPSamplerBase.ARGUMENTS).getObjectValue(); boolean useRaw = el.getPropertyAsBoolean(HTTPSamplerBase.POST_BODY_RAW, HTTPSamplerBase.POST_BODY_RAW_DEFAULT); if(useRaw) { String postBody = computePostBody(arguments, true); // Convert CRLF to CR, see modifyTestElement postBodyContent.setInitialText(postBody); postBodyContent.setCaretPosition(0); argsPanel.clear(); postContentTabbedPane.setSelectedIndex(tabRawBodyIndex, false); } else { postBodyContent.setInitialText(""); argsPanel.configure(arguments); postContentTabbedPane.setSelectedIndex(TAB_PARAMETERS, false); } if(showFileUploadPane) { filesPanel.configure(el); } domain.setText(el.getPropertyAsString(HTTPSamplerBase.DOMAIN)); String portString = el.getPropertyAsString(HTTPSamplerBase.PORT); // Only display the port number if it is meaningfully specified if (portString.equals(HTTPSamplerBase.UNSPECIFIED_PORT_AS_STRING)) { port.setText(""); // $NON-NLS-1$ } else { port.setText(portString); } protocol.setText(el.getPropertyAsString(HTTPSamplerBase.PROTOCOL)); contentEncoding.setText(el.getPropertyAsString(HTTPSamplerBase.CONTENT_ENCODING)); path.setText(el.getPropertyAsString(HTTPSamplerBase.PATH)); if (notConfigOnly){ method.setText(el.getPropertyAsString(HTTPSamplerBase.METHOD)); followRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.FOLLOW_REDIRECTS)); autoRedirects.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.AUTO_REDIRECTS)); useKeepAlive.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.USE_KEEPALIVE)); useMultipart.setSelected(el.getPropertyAsBoolean(HTTPSamplerBase.DO_MULTIPART_POST)); useBrowserCompatibleMultipartMode.setSelected(el.getPropertyAsBoolean( HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART, HTTPSamplerBase.BROWSER_COMPATIBLE_MULTIPART_MODE_DEFAULT)); } } |
long method | long method | t | t | t | 0 | 14061 | https://github.com/apache/jmeter/blob/0facf1525a7d0bd816efd33e72309856e901a883/src/protocol/http/org/apache/jmeter/protocol/http/config/gui/UrlConfigGui.java/#L272-L314 | 1 | 2304 | 14061 | major | ||
| 964 | { "message": "YES I found bad smells", "detected_bad_smells": [ { "1. Long Method": "Long Method detected" }, { "2. Feature Envy": "Feature Envy detected" } ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("unchecked") private void extractDataAndSave(IBatchDAO batchDAO) { if (logger.isDebugEnabled()) { logger.debug("Extract data and save"); } long startTime = System.currentTimeMillis(); try { HistogramMetric.Timer timer = prepareLatency.createTimer(); List batchAllCollection = new LinkedList(); try { List persistenceWorkers = new ArrayList<>(); persistenceWorkers.addAll(IndicatorProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(RecordProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.addAll(TopNProcess.INSTANCE.getPersistentWorkers()); persistenceWorkers.forEach(worker -> { if (logger.isDebugEnabled()) { logger.debug("extract {} worker data and save", worker.getClass().getName()); } if (worker.flushAndSwitch()) { List batchCollection = worker.buildBatchCollection(); if (logger.isDebugEnabled()) { logger.debug("extract {} worker data size: {}", worker.getClass().getName(), batchCollection.size()); } batchAllCollection.addAll(batchCollection); } }); if (debug) { logger.info("build batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } finally { timer.finish(); } HistogramMetric.Timer executeLatencyTimer = executeLatency.createTimer(); try { batchDAO.batchPersistence(batchAllCollection); } finally { executeLatencyTimer.finish(); } } catch (Throwable e) { errorCounter.inc(); logger.error(e.getMessage(), e); } finally { if (logger.isDebugEnabled()) { logger.debug("persistence data save finish"); } } if (debug) { logger.info("batch persistence duration: {} ms", System.currentTimeMillis() - startTime); } } |
long method | 1. long method: long method detected, 2. feature envy: feature envy detected | t | t | t | 2. feature envy: feature envy detected | 0 | 8595 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/storage/PersistenceTimer.java/#L72-L129 | 1 | 964 | 8595 | major | |
| 2187 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @XmlRootElement( name = "artifactTransferRequest" ) public class ArtifactTransferRequest extends Artifact implements Serializable { private String targetRepositoryId; public String getTargetRepositoryId() { return targetRepositoryId; } public void setTargetRepositoryId( String targetRepositoryId ) { this.targetRepositoryId = targetRepositoryId; } } |
data class | data class | t | t | t | 0 | 13438 | https://github.com/apache/archiva/blob/d1242030bf232c0d9b68e4402188ee261924bf4b/archiva-modules/archiva-web/archiva-rest/archiva-rest-api/src/main/java/org/apache/archiva/rest/api/model/ArtifactTransferRequest.java/#L29-L45 | 1 | 2187 | 13438 | minor | ||
| 410 | { "message": "YES I found bad smells", "bad smells are": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class DIRuntimeException extends RuntimeException { private static final long serialVersionUID = 396131653561690312L; /** * Creates new ConfigurationException without detail message. */ public DIRuntimeException() { } /** * Constructs an exception with the specified message with an optional list * of message formatting arguments. Message formatting rules follow * "String.format(..)" conventions. */ public DIRuntimeException(String messageFormat, Object... messageArgs) { super(String.format(messageFormat, messageArgs)); } /** * Constructs an exception wrapping another exception thrown elsewhere. */ public DIRuntimeException(Throwable cause) { super(cause); } public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) { super(String.format(messageFormat, messageArgs), cause); } } |
data class | data class, long method | t | t | t | long method | 0 | 4172 | https://github.com/apache/cayenne/blob/5be5235ed1c02589b6300e9729cf3c308c0173e8/cayenne-di/src/main/java/org/apache/cayenne/di/DIRuntimeException.java/#L26-L55 | 1 | 410 | 4172 | minor | |
| 4197 | {"response": "YES I found bad smells", "detected_bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public final class ResolutionOptions { public static class EncodingStrategy extends TypesafeEnum { private EncodingStrategy(final int value) { super(value); } /** * When this strategy is chosen, the file's existing encoding is used. */ public final static EncodingStrategy DEFAULT = new EncodingStrategy(0); /** * When this strategy is chosen, the all files involved in the merge * will have their encodings treated like the given encoding. No file * conversion is done. */ public final static EncodingStrategy OVERRIDE_EXPLICIT = new EncodingStrategy(1); /** * When this strategy is chosen, the all files involved in the merge * will be converted into the explicitly named encoding. */ public final static EncodingStrategy CONVERT_EXPLICIT = new EncodingStrategy(2); } /** * How to go about resolving encoding conflicts. */ private EncodingStrategy encodingStrategy = EncodingStrategy.DEFAULT; /** * Only used when _encodingStrategy is not default. */ private FileEncoding explicitEncoding = FileEncoding.AUTOMATICALLY_DETECT; private boolean useInternalEngine = true; private FileEncoding acceptMergeEncoding = null; private String newPath = null; private boolean acceptMergeWithConflicts = false; private PropertyValue[] acceptMergeProperties; /** * Creates a {@link ResolutionOptions} with the default options set. */ public ResolutionOptions() { super(); } /** * Sets the strategy for resolving encoding conflicts. If the strategy is * EncodingStrategy.DEFAULT, explicitEncoding must be null. If the strategy * is some other value, explicitEncoding must be non-null, and represents * the overriding encoding, or conversion encoding, or whatever that * strategy's comment says it represents. * * @param strategy * the strategy to take for resolving encoding conflicts. * @param explicitEncoding * the encoding to use for resolving conflicts (null if the strategy * is EncodingStrategy.DEFAULT). */ public void setEncodingStrategy(final EncodingStrategy strategy, final FileEncoding explicitEncoding) { Check.isTrue( (strategy == EncodingStrategy.DEFAULT && explicitEncoding == null || explicitEncoding != null), "explicitEncoding must be null if strategy is EncodingStrategy.DEFAULT"); //$NON-NLS-1$ encodingStrategy = strategy; this.explicitEncoding = explicitEncoding; } /** * Gets the encoding resolution strategy. If the returned strategy is not * EncodingStrategy.DEFAULT, call getExplicitEncoding() to get the encoding * to be used for the strategy. * * @return the encoding resolution strategy. */ public EncodingStrategy getEncodingStrategy() { return encodingStrategy; } /** * Gets the explicit encoding set previously as part of setting an encoding * strategy. * * @return the encoding to use as part of the encoding resolution strategy, * null if not set or if the strategy was EncodingStrategy.DEFAULT. */ public FileEncoding getExplicitEncoding() { return explicitEncoding; } public void setUseInternalEngine(final boolean useInternalEngine) { this.useInternalEngine = useInternalEngine; } public boolean useInternalEngine() { return useInternalEngine; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending encoding change, the given encoding will * be used (no file conversion is done). If the given encoding is null, the * conflict will not be resolved. * * @param encoding * the encoding to use when an automatic merge is desired and there * is a conflicting pending change. */ public void setAcceptMergeEncoding(final FileEncoding encoding) { acceptMergeEncoding = encoding; } /** * Gets the encoding to use when an AcceptMerge resolution is desired but * there is a conflicting pending encoding change. If null is returned, the * encoding should be unchanged. * * @return the encoding to use to resolve the case where AcceptMerge must * operate on a file with a conflicting pending encoding change, * null if the encoding should be unchanged. */ public FileEncoding getAcceptMergeEncoding() { return acceptMergeEncoding; } /** * When a conflict is to be resolved with the AcceptMerge resolution and * there is a conflicting pending property change, this property contains * the desired properties. If this property is left as null, the conflict * will not be resolved. */ public PropertyValue[] getAcceptMergeProperties() { return acceptMergeProperties; } public void setAcceptMergeProperties(final PropertyValue[] acceptMergeProperties) { this.acceptMergeProperties = acceptMergeProperties; } /** * Sets the new path for a conflicted item or the item in its way when it * needs needs to move to a new location. This may happen in cases like * these: * * Merge conflict with AcceptMerge chosen, and there's a conflicting pending * rename: set the desired name. If null, the conflict will not be resolved. * * Namespace conflict with AcceptTheirs: set the path that would describe * their item. * * Namespace conflict with AcceptYours: set to the path of the local item * that was in the way of the server item. * * @param newPath * the path to use for this conflict resolution, null to defer the * resolution in the cases documented above. */ public void setNewPath(final String newPath) { this.newPath = newPath; } /** * Gets the new path to use for this resolution. See setNewPath() comments * for details. * * @return the new path, null if not set. */ public String getNewPath() { return newPath; } /** * @return true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public boolean isAcceptMergeWithConflicts() { return acceptMergeWithConflicts; } /** * Sets the option to accept (resolve a conflict) when the merge resulted in * conflicts. * * @param mergeWithConflicts * true if a merge should be resolved when conflicts remain in the * file, false if the merge should not be resolved when conflicts * remain */ public void setAcceptMergeWithConflicts(final boolean mergeWithConflicts) { acceptMergeWithConflicts = mergeWithConflicts; } } |
data class | data class | t | t | t | 0 | 11045 | https://github.com/Microsoft/team-explorer-everywhere/blob/89ab2a4847aec8ec2afdf36c3f6287dd03bd558d/source/com.microsoft.tfs.core/src/com/microsoft/tfs/core/clients/versioncontrol/ResolutionOptions.java/#L17-L213 | 1 | 4197 | 11045 | critical | ||
| 1824 | { "output": "YES I found bad smells", "detected_bad_smells": [ "the bad smells are:", "1. Blob" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public abstract class PersistentReplicatedTestBase extends JUnit4CacheTestCase { protected static final int MAX_WAIT = 60 * 1000; protected static String REGION_NAME = "region"; protected File diskDir; protected static String SAVED_ACK_WAIT_THRESHOLD; @Override public final void postSetUp() throws Exception { Invoke.invokeInEveryVM(PersistentReplicatedTestBase.class, "setRegionName", new Object[] {getUniqueName()}); setRegionName(getUniqueName()); diskDir = new File("diskDir-" + getName()).getAbsoluteFile(); FileUtils.deleteDirectory(diskDir); diskDir.mkdir(); diskDir.deleteOnExit(); } public static void setRegionName(String testName) { REGION_NAME = testName + "Region"; } @Override public final void postTearDownCacheTestCase() throws Exception { FileUtils.deleteDirectory(diskDir); postTearDownPersistentReplicatedTestBase(); } protected void postTearDownPersistentReplicatedTestBase() throws Exception {} protected void waitForBlockedInitialization(VM vm) { vm.invoke(new SerializableRunnable() { @Override public void run() { GeodeAwaitility.await().untilAsserted(new WaitCriterion() { @Override public String description() { return "Waiting for another persistent member to come online"; } @Override public boolean done() { GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); PersistentMemberManager mm = cache.getPersistentMemberManager(); Map> regions = mm.getWaitingRegions(); boolean done = !regions.isEmpty(); return done; } }); } }); } protected SerializableRunnable createPersistentRegionWithoutCompaction(final VM vm0) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm0); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); dsf.setAutoCompact(false); dsf.setAllowForceCompaction(true); dsf.setCompactionThreshold(20); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm0.invoke(createRegion); return createRegion; } protected void closeRegion(final VM vm) { SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") { @Override public void run() { Cache cache = getCache(); Region region = cache.getRegion(REGION_NAME); region.close(); } }; vm.invoke(closeRegion); } protected void closeCache(final VM vm) { SerializableRunnable closeCache = new SerializableRunnable("close cache") { @Override public void run() { Cache cache = getCache(); cache.close(); } }; vm.invoke(closeCache); } protected AsyncInvocation closeCacheAsync(VM vm0) { SerializableRunnable close = new SerializableRunnable() { @Override public void run() { Cache cache = getCache(); cache.close(); } }; return vm0.invokeAsync(close); } protected void createNonPersistentRegion(VM vm) throws Exception { SerializableRunnable createRegion = new SerializableRunnable("Create non persistent region") { @Override public void run() { Cache cache = getCache(); RegionFactory rf = new RegionFactory(); rf.setDataPolicy(DataPolicy.REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; vm.invoke(createRegion); } protected AsyncInvocation createPersistentRegionWithWait(VM vm) throws Exception { return _createPersistentRegion(vm, true); } protected void createPersistentRegion(VM vm) throws Exception { _createPersistentRegion(vm, false); } private AsyncInvocation _createPersistentRegion(VM vm, boolean wait) throws Exception { AsyncInvocation future = createPersistentRegionAsync(vm); long waitTime = wait ? 500 : MAX_WAIT; future.join(waitTime); if (future.isAlive() && !wait) { fail("Region not created within" + MAX_WAIT); } if (!future.isAlive() && wait) { fail("Did not expect region creation to complete"); } if (!wait && future.exceptionOccurred()) { throw new RuntimeException(future.getException()); } return future; } protected AsyncInvocation createPersistentRegionAsync(final VM vm) { SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") { @Override public void run() { Cache cache = getCache(); DiskStoreFactory dsf = cache.createDiskStoreFactory(); File dir = getDiskDirForVM(vm); dir.mkdirs(); dsf.setDiskDirs(new File[] {dir}); dsf.setMaxOplogSize(1); DiskStore ds = dsf.create(REGION_NAME); RegionFactory rf = new RegionFactory(); rf.setDiskStoreName(ds.getName()); rf.setDiskSynchronous(true); rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); rf.setScope(Scope.DISTRIBUTED_ACK); rf.create(REGION_NAME); } }; return vm.invokeAsync(createRegion); } protected File getDiskDirForVM(final VM vm) { File dir = new File(diskDir, String.valueOf(vm.getId())); return dir; } protected void backupDir(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); FileUtils.copyDirectory(dirForVM, backFile); } protected void restoreBackup(VM vm) throws IOException { File dirForVM = getDiskDirForVM(vm); File backFile = new File(dirForVM.getParent(), dirForVM.getName() + ".bk"); if (!backFile.renameTo(dirForVM)) { FileUtils.deleteDirectory(dirForVM); FileUtils.copyDirectory(backFile, dirForVM); FileUtils.deleteDirectory(backFile); } } } |
blob | the bad smells are:, 1 Blob | t | f | t | the bad smells are: | 0 | 12104 | https://github.com/apache/geode/blob/8fd839e8b73e40bd2dfd14f331b587431bd35a66/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/persistence/PersistentReplicatedTestBase.java/#L42-L242 | 1 | 1824 | 12104 | minor | |
| 1859 | {"response": "YES I found bad smells", "detected_bad_smells": ["Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public PigServer(PigContext context, boolean connect) throws ExecException { this.pigContext = context; currDAG = new Graph(false); jobName = pigContext.getProperties().getProperty( PigContext.JOB_NAME, PigContext.JOB_NAME_PREFIX + ":DefaultJobName"); if (connect) { pigContext.connect(); } this.filter = new BlackAndWhitelistFilter(this); addHadoopProperties(); addJarsFromProperties(); markPredeployedJarsFromProperties(); if (ScriptState.get() == null) { // If Pig was started via command line, ScriptState should have been // already initialized in Main. If so, we should not overwrite it. ScriptState.start(pigContext.getExecutionEngine().instantiateScriptState()); } PigStats.start(pigContext.getExecutionEngine().instantiatePigStats()); // log ATS event includes the caller context String auditId = PigATSClient.getPigAuditId(pigContext); String callerId = (String)pigContext.getProperties().get(PigConfiguration.PIG_LOG_TRACE_ID); log.info("Pig Script ID for the session: " + auditId); if (callerId != null) { log.info("Caller ID for session: " + callerId); } if (Boolean.parseBoolean(pigContext.getProperties() .getProperty(PigConfiguration.PIG_ATS_ENABLED))) { if (Boolean.parseBoolean(pigContext.getProperties() .getProperty("yarn.timeline-service.enabled", "false"))) { PigATSClient.ATSEvent event = new PigATSClient.ATSEvent(auditId, callerId); try { PigATSClient.getInstance().logEvent(event); } catch (Exception e) { log.warn("Error posting to ATS: ", e); } } else { log.warn("ATS is disabled since" + " yarn.timeline-service.enabled set to false"); } } // set hdfs caller context Class callerContextClass = null; try { callerContextClass = Class.forName("org.apache.hadoop.ipc.CallerContext"); } catch (ClassNotFoundException e) { // If pre-Hadoop 2.8.0, skip setting CallerContext } if (callerContextClass != null) { try { // Reflection for the following code since it is only available since hadoop 2.8.0: // CallerContext hdfsContext = new CallerContext.Builder(auditId).build(); // CallerContext.setCurrent(hdfsContext); Class callerContextBuilderClass = Class.forName("org.apache.hadoop.ipc.CallerContext$Builder"); Constructor callerContextBuilderConstruct = callerContextBuilderClass.getConstructor(String.class); Object builder = callerContextBuilderConstruct.newInstance(auditId); Method builderBuildMethod = builder.getClass().getMethod("build"); Object hdfsContext = builderBuildMethod.invoke(builder); Method callerContextSetCurrentMethod = callerContextClass.getMethod("setCurrent", hdfsContext.getClass()); callerContextSetCurrentMethod.invoke(callerContextClass, hdfsContext); } catch (Exception e) { // Shall not happen unless API change in future Hadoop commons throw new ExecException(e); } } } |
long method | long method | t | t | t | 0 | 12219 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/PigServer.java/#L223-L296 | 1 | 1859 | 12219 | major | ||
| 605 | { "message": "YES I found bad smells", "bad smells are": [ "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public int next() { final int startNode = _startNode; if (_startNode == NULL) { return NULL; } int node = _currentNode; int expType; final int nodeType = _nodeType; if (nodeType != DTM.ELEMENT_NODE) { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType != nodeType); } // %OPT% If the start node is root (e.g. in the case of //node), // we can save the isDescendant() check, because all nodes are // descendants of root. else if (startNode == DTMDefaultBase.ROOTNODE) { do { node++; expType = _exptype2(node); if (NULL == expType) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } else { do { node++; expType = _exptype2(node); if (NULL == expType || _parent2(node) < startNode && startNode != node) { _currentNode = NULL; return END; } } while (expType < DTM.NTYPES || m_extendedTypes[expType].getNodeType() != DTM.ELEMENT_NODE); } _currentNode = node; return returnNode(makeNodeHandle(node)); } |
long method | long method | t | t | t | 0 | 6050 | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java/#L1658-L1719 | 1 | 605 | 6050 | minor | ||
| 1993 | YES I found bad smells The bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void cleanup() { for (final BundleWire requiredWire : requiredWires.getAllValues()) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) requiredWire).providerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } for (final BundleWire hostWire : providedWires .lookup(HostNamespace.HOST_NAMESPACE)) { final ConciergeBundleWiring bw = ((ConciergeBundleWire) hostWire).requirerWiring; if (bw != null) { bw.inUseSet.remove(revision); } } } |
feature envy | Feature envy | t | f | t | 0 | 12691 | https://github.com/eclipse/concierge/blob/4c73cacebc5ecbdef24d4256ab506359294f7a55/framework/org.eclipse.concierge/src/org/eclipse/concierge/Resources.java/#L626-L640 | 2 | 1993 | 12691 | minor | ||
| 298 | {"message": "YES I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Deprecated public class TransactionRecord { // Commit Log Offset private long offset; private String producerGroup; public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } } |
data class | data class | t | t | t | 0 | 3132 | https://github.com/apache/rocketmq/blob/971fa8ed8b209b39bdfe41c57cd64576d244e6bd/broker/src/main/java/org/apache/rocketmq/broker/transaction/TransactionRecord.java/#L22-L43 | 1 | 298 | 3132 | major | ||
| 2493 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @SuppressWarnings("serial") public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut implements PointcutAdvisor, Ordered, Serializable { private Advice advice = EMPTY_ADVICE; private int order = Ordered.LOWEST_PRECEDENCE; /** * Create a new StaticMethodMatcherPointcutAdvisor, * expecting bean-style configuration. * @see #setAdvice */ public StaticMethodMatcherPointcutAdvisor() { } /** * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. * @param advice the Advice to use */ public StaticMethodMatcherPointcutAdvisor(Advice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } public void setAdvice(Advice advice) { this.advice = advice; } @Override public Advice getAdvice() { return this.advice; } @Override public boolean isPerInstance() { return true; } @Override public Pointcut getPointcut() { return this; } } |
data class | blob, data class | t | t | t | blob | 0 | 14624 | https://github.com/spring-projects/spring-framework/blob/3a0f309e2c9fdbbf7fb2d348be861528177f8555/spring-aop/src/main/java/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java/#L35-L90 | 1 | 2493 | 14624 | minor | |
| 1923 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: void setStackMap(StackMapTable_attribute attr) { if (attr == null) { map = null; return; } Method m = classWriter.getMethod(); Descriptor d = m.descriptor; String[] args; try { ConstantPool cp = classWriter.getClassFile().constant_pool; String argString = d.getParameterTypes(cp); args = argString.substring(1, argString.length() - 1).split("[, ]+"); } catch (ConstantPoolException | InvalidDescriptor e) { return; } boolean isStatic = m.access_flags.is(AccessFlags.ACC_STATIC); verification_type_info[] initialLocals = new verification_type_info[(isStatic ? 0 : 1) + args.length]; if (!isStatic) initialLocals[0] = new CustomVerificationTypeInfo("this"); for (int i = 0; i < args.length; i++) { initialLocals[(isStatic ? 0 : 1) + i] = new CustomVerificationTypeInfo(args[i].replace(".", "/")); } map = new HashMap<>(); StackMapBuilder builder = new StackMapBuilder(); // using -1 as the pc for the initial frame effectively compensates for // the difference in behavior for the first stack map frame (where the // pc offset is just offset_delta) compared to subsequent frames (where // the pc offset is always offset_delta+1). int pc = -1; map.put(pc, new StackMap(initialLocals, empty)); for (int i = 0; i < attr.entries.length; i++) pc = attr.entries[i].accept(builder, pc); } |
long method | Long method2 Feature envy | t | f | t | 0 | 12426 | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/javap/StackMapWriter.java/#L72-L111 | 2 | 1923 | 12426 | minor | ||
| 1564 | { "message": "YES I found bad smells", "bad_smells": [ "Data Class", "Long Method" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class IgfsHandshakeResponse implements Externalizable { /** */ private static final long serialVersionUID = 0L; /** IGFS name. */ private String igfsName; /** Server block size. */ private long blockSize; /** Whether to force sampling on client's side. */ private Boolean sampling; /** * {@link Externalizable} support. */ public IgfsHandshakeResponse() { // No-op. } /** * Constructor. * * @param blockSize Server default block size. */ public IgfsHandshakeResponse(String igfsName, long blockSize, Boolean sampling) { this.igfsName = igfsName; this.blockSize = blockSize; this.sampling = sampling; } /** * @return IGFS name. */ public String igfsName() { return igfsName; } /** * @return Server default block size. */ public long blockSize() { return blockSize; } /** * @return Sampling flag. */ public Boolean sampling() { return sampling; } /** {@inheritDoc} */ @Override public void writeExternal(ObjectOutput out) throws IOException { U.writeString(out, igfsName); out.writeLong(blockSize); if (sampling != null) { out.writeBoolean(true); out.writeBoolean(sampling); } else out.writeBoolean(false); } /** {@inheritDoc} */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { igfsName = U.readString(in); blockSize = in.readLong(); if (in.readBoolean()) sampling = in.readBoolean(); } } |
data class | Data Class, Long Method | t | f | t | Long Method | 0 | 11320 | https://github.com/apache/ignite/blob/7a7c407ea41477aae8508bfe871b4e9a67e1b277/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsHandshakeResponse.java/#L29-L104 | 1 | 1564 | 11320 | minor | |
| 122 | {"response": "YES I found bad smells", "bad smells are:": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: @Data static class VaultInitializationResponseImpl implements VaultInitializationResponse { private List keys = new ArrayList<>(); @JsonProperty("root_token") private String rootToken = ""; public VaultToken getRootToken() { return VaultToken.of(rootToken); } } |
data class | data class | t | t | t | 0 | 1535 | https://github.com/spring-projects/spring-vault/blob/6e36eb10b02c6931c3b565c5d9d76f5e217bf309/spring-vault-core/src/main/java/org/springframework/vault/core/VaultSysTemplate.java/#L414-L425 | 1 | 122 | 1535 | major | ||
| 24 | { "message": "YES I found bad smells", "bad smells are": "3. Blob, 4. Data Class" } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class Ipam { private String driver; private List config; private Map options; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public Ipam withDriver(String driver) { this.driver = driver; return this; } public List getConfig() { return config; } public void setConfig(List config) { this.config = config; } public Ipam withConfig(List config) { this.config = config; return this; } public Map getOptions() { return options; } public void setOptions(Map options) { this.options = options; } public Ipam withOptions(Map options) { this.options = options; return this; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Ipam)) { return false; } final Ipam that = (Ipam) obj; return Objects.equals(driver, that.driver) && getConfig().equals(that.getConfig()) && getOptions().equals(that.getOptions()); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(driver); hash = 31 * hash + getConfig().hashCode(); hash = 31 * hash + getOptions().hashCode(); return hash; } @Override public String toString() { return "Ipam{" + "driver='" + driver + '\'' + ", config=" + config + ", options=" + options + '}'; } } |
data class | 3. blob, 4. data class | t | t | t | 3. blob | 0 | 691 | https://github.com/eclipse/che/blob/c5498c2ac562cd8a2fc79a6bb0446d291f05a201/infrastructures/docker/docker-client/src/main/java/org/eclipse/che/infrastructure/docker/client/json/network/Ipam.java/#L19-L98 | 1 | 24 | 691 | critical | |
| 954 | YES I found bad smells the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static Class stringToClass(String klass) throws FrontendException { if ("string".equalsIgnoreCase(klass)) { return String.class; } else if ("int".equalsIgnoreCase(klass)) { return Integer.TYPE; } else if ("double".equalsIgnoreCase(klass)) { return Double.TYPE; } else if ("float".equalsIgnoreCase(klass)){ return Float.TYPE; } else if ("long".equalsIgnoreCase(klass)) { return Long.TYPE; } else if ("double[]".equalsIgnoreCase(klass)) { return DOUBLE_ARRAY_CLASS; } else if ("int[]".equalsIgnoreCase(klass)) { return INT_ARRAY_CLASS; } else if ("long[]".equalsIgnoreCase(klass)) { return LONG_ARRAY_CLASS; } else if ("float[]".equalsIgnoreCase(klass)) { return FLOAT_ARRAY_CLASS; } else if ("string[]".equalsIgnoreCase(klass)) { return STRING_ARRAY_CLASS; } else { throw new FrontendException("unable to find matching class for " + klass); } } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 8530 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/builtin/Invoker.java/#L113-L138 | 2 | 954 | 8530 | minor | ||
| 2345 | {"response": "YES, I found bad smells. The bad smells are: 1. Long Method"} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: private void removeAndReconnect(MapReduceOper mr, MapReduceOper newMR) throws VisitorException { List mapperSuccs = getPlan().getSuccessors(mr); List mapperPreds = getPlan().getPredecessors(mr); // make a copy before removing operator ArrayList succsCopy = null; ArrayList predsCopy = null; if (mapperSuccs != null) { succsCopy = new ArrayList(mapperSuccs); } if (mapperPreds != null) { predsCopy = new ArrayList(mapperPreds); } getPlan().remove(mr); // reconnect the mapper's successors if (succsCopy != null) { for (MapReduceOper succ : succsCopy) { try { getPlan().connect(newMR, succ); } catch (PlanException e) { int errCode = 2133; String msg = "Internal Error. Unable to connect map plan with successors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } // reconnect the mapper's predecessors if (predsCopy != null) { for (MapReduceOper pred : predsCopy) { if (newMR.getOperatorKey().equals(pred.getOperatorKey())) { continue; } try { getPlan().connect(pred, newMR); } catch (PlanException e) { int errCode = 2134; String msg = "Internal Error. Unable to connect map plan with predecessors for optimization."; throw new OptimizerException(msg, errCode, PigException.BUG, e); } } } mergeMROperProperties(mr, newMR); } |
long method | 1. long method | t | t | t | 0 | 14192 | https://github.com/apache/pig/blob/17a4d1795ead1f2b4c62043eaf4739ed39ec2f3f/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/MultiQueryOptimizer.java/#L1096-L1141 | 1 | 2345 | 14192 | major | ||
| 1400 | YES I found bad smells the bad smells are: 1. Long method, 2. Duplicate code. | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Test public void writeRead() throws IOException { try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { XSSFSheet sheet1 = workbook.getSheetAt(0); XSSFSheet sheet2 = workbook.getSheetAt(1); assertTrue(sheet1.hasComments()); assertFalse(sheet2.hasComments()); // Change on comment on sheet 1, and add another into // sheet 2 Row r5 = sheet1.getRow(4); Comment cc5 = r5.getCell(2).getCellComment(); cc5.setAuthor("Apache POI"); cc5.setString(new XSSFRichTextString("Hello!")); Row r2s2 = sheet2.createRow(2); Cell c1r2s2 = r2s2.createCell(1); assertNull(c1r2s2.getCellComment()); Drawing dg = sheet2.createDrawingPatriarch(); Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); cc2.setAuthor("Also POI"); cc2.setString(new XSSFRichTextString("A new comment")); c1r2s2.setCellComment(cc2); // Save, and re-load the file try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { // Check we still have comments where we should do sheet1 = workbookBack.getSheetAt(0); sheet2 = workbookBack.getSheetAt(1); assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); // And check they still have the contents they should do assertEquals("Apache POI", sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); assertEquals("Nick Burch", sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); assertEquals("Also POI", sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); assertEquals("Hello!", sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); } } } |
long method | Long method, 2 Duplicate code | t | f | t | 2. Duplicate code. | 0 | 10859 | https://github.com/apache/poi/blob/351623a86924dab9c565e08e8cecfe151522c448/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java/#L128-L175 | 2 | 1400 | 10859 | major | |
| 821 | {"response": "YES I found bad smells", "bad_smells are": ["Data Class", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class LimitedSizeDataCollection implements SWCollection { private final HashMap> data; private final int limitedSize; private volatile boolean writing; private volatile boolean reading; LimitedSizeDataCollection(int limitedSize) { this.data = new HashMap<>(); this.writing = false; this.reading = false; this.limitedSize = limitedSize; } public void finishWriting() { writing = false; } @Override public void writing() { writing = true; } @Override public boolean isWriting() { return writing; } @Override public void finishReading() { reading = false; } @Override public void reading() { reading = true; } @Override public boolean isReading() { return reading; } @Override public int size() { return data.size(); } @Override public void clear() { data.clear(); } @Override public boolean containsKey(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support containsKey operation."); } @Override public STORAGE_DATA get(STORAGE_DATA key) { throw new UnsupportedOperationException("Limited size data collection doesn't support get operation."); } @Override public void put(STORAGE_DATA value) { LinkedList storageDataList = this.data.get(value); if (storageDataList == null) { storageDataList = new LinkedList<>(); data.put(value, storageDataList); } if (storageDataList.size() < limitedSize) { storageDataList.add(value); return; } for (int i = 0; i < storageDataList.size(); i++) { STORAGE_DATA storageData = storageDataList.get(i); if (value.compareTo(storageData) <= 0) { if (i == 0) { // input value is less than the smallest in top N list, ignore } else { // Remove the smallest in top N list // add the current value into the right position storageDataList.add(i, value); storageDataList.removeFirst(); } return; } } // Add the value as biggest in top N list storageDataList.addLast(value); storageDataList.removeFirst(); } @Override public Collection collection() { List collection = new ArrayList<>(); data.values().forEach(e -> e.forEach(collection::add)); return collection; } } |
data class | data class, long method | t | t | t | long method | 0 | 7686 | https://github.com/apache/incubator-skywalking/blob/32c4bced8a7e055003d6e4bea0fd8f8361bec8e5/oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/data/LimitedSizeDataCollection.java/#L24-L115 | 1 | 821 | 7686 | major | |
| 300 | {"response": "YES I found bad smells", "detected_bad_smells": ["Blob"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class HistoryClientService extends AbstractService { private static final Log LOG = LogFactory.getLog(HistoryClientService.class); private HSClientProtocol protocolHandler; private Server server; private WebApp webApp; private InetSocketAddress bindAddress; private HistoryContext history; private JHSDelegationTokenSecretManager jhsDTSecretManager; public HistoryClientService(HistoryContext history, JHSDelegationTokenSecretManager jhsDTSecretManager) { super("HistoryClientService"); this.history = history; this.protocolHandler = new HSClientProtocolHandler(); this.jhsDTSecretManager = jhsDTSecretManager; } protected void serviceStart() throws Exception { Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); initializeWebApp(conf); InetSocketAddress address = conf.getSocketAddr( JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_PORT); server = rpc.getServer(HSClientProtocol.class, protocolHandler, address, conf, jhsDTSecretManager, conf.getInt(JHAdminConfig.MR_HISTORY_CLIENT_THREAD_COUNT, JHAdminConfig.DEFAULT_MR_HISTORY_CLIENT_THREAD_COUNT)); // Enable service authorization? if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(conf, new ClientHSPolicyProvider()); } server.start(); this.bindAddress = conf.updateConnectAddr(JHAdminConfig.MR_HISTORY_BIND_HOST, JHAdminConfig.MR_HISTORY_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_ADDRESS, server.getListenerAddress()); LOG.info("Instantiated HistoryClientService at " + this.bindAddress); super.serviceStart(); } @VisibleForTesting protected void initializeWebApp(Configuration conf) { webApp = new HsWebApp(history); InetSocketAddress bindAddress = MRWebAppUtil.getJHSWebBindAddress(conf); // NOTE: there should be a .at(InetSocketAddress) WebApps .$for("jobhistory", HistoryClientService.class, this, "ws") .with(conf) .withHttpSpnegoKeytabKey( JHAdminConfig.MR_WEBAPP_SPNEGO_KEYTAB_FILE_KEY) .withHttpSpnegoPrincipalKey( JHAdminConfig.MR_WEBAPP_SPNEGO_USER_NAME_KEY) .at(NetUtils.getHostPortString(bindAddress)).start(webApp); String connectHost = MRWebAppUtil.getJHSWebappURLWithoutScheme(conf).split(":")[0]; MRWebAppUtil.setJHSWebappURLWithoutScheme(conf, connectHost + ":" + webApp.getListenerAddress().getPort()); } @Override protected void serviceStop() throws Exception { if (server != null) { server.stop(); } if (webApp != null) { webApp.stop(); } super.serviceStop(); } @Private public MRClientProtocol getClientHandler() { return this.protocolHandler; } @Private public InetSocketAddress getBindAddress() { return this.bindAddress; } private class HSClientProtocolHandler implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId()); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId()); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId); Collection tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token realJHSToken = new Token(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token token = new Token( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } } |
blob | blob | t | t | t | 0 | 3154 | https://github.com/apache/hadoop-common/blob/42a61a4fbc88303913c4681f0d40ffcc737e70b5/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java/#L99-L435 | 1 | 300 | 3154 | critical | ||
| 1521 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: private static boolean resolveGenericRef(GenericRef ref, Class clazz, Type type) { if (type instanceof Class) { if (type == ref.ifaceClass) { // is this a straight ref or a TypeVariable? // debug("Found ref (as class): %s",toShortName(type)); ref.setGenericFromType(type,0); return true; } else { // Keep digging return resolveGenericRef(ref,type); } } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType)type; Type rawType = ptype.getRawType(); if (rawType == ref.ifaceClass) { // debug("Found ref on [%s] as ParameterizedType [%s]",toShortName(clazz),toShortName(ptype)); // Always get the raw type parameter, let unwrap() solve for what it is ref.setGenericFromType(ptype.getActualTypeArguments()[0],0); return true; } else { // Keep digging return resolveGenericRef(ref,rawType); } } return false; } |
feature envy | Long method2 Feature envy | t | f | t | 0 | 11173 | https://github.com/eclipse/jetty.project/blob/65528f76c5ef6ddca11385f9721c8f0bc5f2eed7/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/util/ReflectUtils.java/#L189-L225 | 2 | 1521 | 11173 | minor | ||
| 225 | {"message": "YES, I found bad smells", "bad smells are": ["Long Method", "Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TwitterPullRecordReader implements IRecordReader { private Query query; private Twitter twitter; private int requestInterval = 5; // seconds private QueryResult result; private int nextTweetIndex = 0; private long lastTweetIdReceived = 0; private CharArrayRecord record; private boolean stopped = false; public TwitterPullRecordReader(Twitter twitter, String keywords, int requestInterval) { this.twitter = twitter; this.requestInterval = requestInterval; this.query = new Query(keywords); this.query.setCount(100); this.record = new CharArrayRecord(); } @Override public void close() throws IOException { // do nothing } @Override public boolean hasNext() throws Exception { return !stopped; } @Override public IRawRecord next() throws IOException, InterruptedException { if (result == null || nextTweetIndex >= result.getTweets().size()) { Thread.sleep(1000 * requestInterval); query.setSinceId(lastTweetIdReceived); try { result = twitter.search(query); } catch (TwitterException e) { throw HyracksDataException.create(e); } nextTweetIndex = 0; } if (result != null && !result.getTweets().isEmpty()) { List tw = result.getTweets(); Status tweet = tw.get(nextTweetIndex++); if (lastTweetIdReceived < tweet.getId()) { lastTweetIdReceived = tweet.getId(); } String jsonTweet = TwitterObjectFactory.getRawJSON(tweet); // transform tweet obj to json record.set(jsonTweet); return record; } else { return null; } } @Override public boolean stop() { stopped = true; return true; } @Override public void setFeedLogManager(FeedLogManager feedLogManager) { // do nothing } @Override public void setController(AbstractFeedDataFlowController controller) { // do nothing } @Override public boolean handleException(Throwable th) { return false; } } |
data class | long method, data class | t | t | t | long method | 0 | 2434 | https://github.com/apache/asterixdb/blob/223d13a06c4a4a58408aeac19674ac1f36f5ff35/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/twitter/TwitterPullRecordReader.java/#L38-L113 | 1 | 225 | 2434 | minor | |
| 563 | {"response": "YES, I found bad smells", "bad_smells": ["Data Class"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class OdaDimensionState extends ReportElementState { /** * The dimension being created. */ protected Dimension element = null; /** * Constructs dimension state with the design parser handler, the container * element and the container property name of the report element. * * @param handler * the design file parser handler * @param theContainer * the element that contains this one * @param prop * the slot in which this element appears */ public OdaDimensionState( ModuleParserHandler handler, DesignElement theContainer, String prop ) { super( handler, theContainer, prop ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.parser.ReportElementState#getElement() */ public DesignElement getElement( ) { return element; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.util.AbstractParseState#parseAttrs(org.xml.sax.Attributes) */ public void parseAttrs( Attributes attrs ) throws XMLParserException { element = new OdaDimension( ); initElement( attrs, true ); } } |
data class | data class | t | t | t | 0 | 5681 | https://github.com/eclipse/birt/blob/f89264810347de98702db45386a822aabc0fadbf/model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/parser/OdaDimensionState.java/#L25-L74 | 1 | 563 | 5681 | minor | ||
| 2245 | { "message": "YES, I found bad smells", "bad smells are": [ "Data Class" ] } | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class TransportConnectionState extends org.apache.activemq.state.ConnectionState { private ConnectionContext context; private TransportConnection connection; private AtomicInteger referenceCounter = new AtomicInteger(); private final Object connectionMutex = new Object(); public TransportConnectionState(ConnectionInfo info, TransportConnection transportConnection) { super(info); connection = transportConnection; } public ConnectionContext getContext() { return context; } public TransportConnection getConnection() { return connection; } public void setContext(ConnectionContext context) { this.context = context; } public void setConnection(TransportConnection connection) { this.connection = connection; } public int incrementReference() { return referenceCounter.incrementAndGet(); } public int decrementReference() { return referenceCounter.decrementAndGet(); } public AtomicInteger getReferenceCounter() { return referenceCounter; } public void setReferenceCounter(AtomicInteger referenceCounter) { this.referenceCounter = referenceCounter; } public Object getConnectionMutex() { return connectionMutex; } } |
data class | data class | t | t | t | 0 | 13647 | https://github.com/apache/activemq/blob/ccf56875b0660214e0a61bd2f8adc418143551fc/activemq-broker/src/main/java/org/apache/activemq/broker/TransportConnectionState.java/#L27-L74 | 1 | 2245 | 13647 | major | ||
| 383 | YES I found bad smells. the bad smells are: 1. Long method 2. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: protected boolean downloadLog(HttpServletRequest request, HttpServletResponse response, ILogService logService, String appenderName) throws ServletException { FileAppender appender = logService .getFileAppender(appenderName); if (appender == null) { String msg = NLS.bind("Appender not found: {0}", appenderName); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); return statusHandler.handleRequest(request, response, error); } File logFile = new File(appender.getFile()); try { LogUtils.provideLogFile(logFile, response); } catch (Exception ex) { String msg = NLS.bind("An error occured when looking for log {0}.", logFile.getName()); final ServerStatus error = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex); LogHelper.log(error); return statusHandler.handleRequest(request, response, error); } return true; } |
long method | Long method2 Feature envy | t | f | t | 0 | 3920 | https://github.com/eclipse/orion.server/blob/24624b85e0d543e8f3cea2bc30f3f589b37de4f0/bundles/org.eclipse.orion.server.logs/src/org/eclipse/orion/server/logs/servlets/FileAppenderHandler.java/#L43-L70 | 2 | 383 | 3920 | minor | ||
| 438 | {"response": "YES I found bad smells", "bad smells are": ["Blob", "Long Method"]} | The list below presents common code smells (aka bad smells) I need to check if the Java code provided at the end of the input contains at least one of them. * Blob * Data Class * Feature Envy * Long Method Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with “YES I found bad smells” when you find any bad smell. Otherwise, start your answer with “NO, I did not find any bad smell”. When you start to list the detected bad smells, always put in your answer “the bad smells are:” amongst the text your answer and always separate it in this format: 1. Long method, 2.Feature envy: public class SCOMMetricHelper { private static final String SQLSERVER_PROPERTIES_FILE = "sqlserver_properties.json"; private static final String JMX_PROPERTIES_FILE = "jmx_properties.json"; private static final Map>> JMX_PROPERTY_IDS = readPropertyProviderIds(JMX_PROPERTIES_FILE); private static final Map>> SQLSERVER_PROPERTY_IDS = readPropertyProviderIds(SQLSERVER_PROPERTIES_FILE); public static Map> getSqlServerPropertyIds(Resource.Type resourceType) { return SQLSERVER_PROPERTY_IDS.get(resourceType.getInternalType()); } public static Map> getJMXPropertyIds(Resource.Type resourceType) { return JMX_PROPERTY_IDS.get(resourceType.getInternalType()); } protected static class Metric { private String metric; private boolean pointInTime; private boolean temporal; private Metric() { } protected Metric(String metric, boolean pointInTime, boolean temporal) { this.metric = metric; this.pointInTime = pointInTime; this.temporal = temporal; } public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public boolean isPointInTime() { return pointInTime; } public void setPointInTime(boolean pointInTime) { this.pointInTime = pointInTime; } public boolean isTemporal() { return temporal; } public void setTemporal(boolean temporal) { this.temporal = temporal; } } private static Map>> readPropertyProviderIds(String filename) { ObjectMapper mapper = new ObjectMapper(); try { Map>> resourceMetricMap = mapper.readValue(ClassLoader.getSystemResourceAsStream(filename), new TypeReference>>>() {}); Map>> resourceMetrics = new HashMap>>(); for (Map.Entry>> resourceEntry : resourceMetricMap.entrySet()) { Map> componentMetrics = new HashMap>(); for (Map.Entry> componentEntry : resourceEntry.getValue().entrySet()) { Map metrics = new HashMap(); for (Map.Entry metricEntry : componentEntry.getValue().entrySet()) { String property = metricEntry.getKey(); Metric metric = metricEntry.getValue(); metrics.put(property, new PropertyInfo(metric.getMetric(), metric.isTemporal(), metric.isPointInTime())); } componentMetrics.put(componentEntry.getKey(), metrics); } resourceMetrics.put(resourceEntry.getKey(), componentMetrics); } return resourceMetrics; } catch (IOException e) { throw new IllegalStateException("Can't read properties file " + filename, e); } } } |
blob | blob, long method | t | t | t | long method | 0 | 4293 | https://github.com/apache/ambari/blob/2bc4779a1e6aabe638101fc8b0e28cd1963d6b13/contrib/ambari-scom/ambari-scom-server/src/main/java/org/apache/ambari/scom/utilities/SCOMMetricHelper.java/#L32-L119 | 1 | 438 | 4293 | critical | |
| 426 | YES, I found bad smells the bad smells are: 1. Feature envy | I need to check if the Java code below contains code smells (aka bad smells). Could you please identify which smells occur in the following code? However, do not describe the smells, just list them. Please start your answer with "YES I found bad smells" when you find any bad smell. Otherwise, start your answer with "NO, I did not find any bad smell". When you start to list the detected bad smells, always put in your answer "the bad smells are:" amongst the text your answer and always separate it in this format: 1.Long method, 2.Feature envy: @Override public boolean equals(Object that) { if( !(that instanceof PlanningCoCodingGroup) ) return false; PlanningCoCodingGroup thatgrp = (PlanningCoCodingGroup) that; return Arrays.equals(_colIndexes, thatgrp._colIndexes); } |
feature envy | Feature envy | t | f | t | 0 | 4264 | https://github.com/apache/systemml/blob/7fba4b29d653747a9ed038d282954a44fea3031c/src/main/java/org/apache/sysml/runtime/compress/cocode/PlanningCoCodingGroup.java/#L116-L123 | 2 | 426 | 4264 | minor |
(2332 rows)